新版的JavaScript API里提供了一个全新的可以实现ajax的API——fetch,这个api采用了全新的 Promise 架构,使用起来更方便,更灵活,详细用法请参考《你不需要jQuery(三):新AJAX方法fetch() 》。
>>>>JSON
jQuery
$.getJSON('/my/url', function(data) { });
谷歌浏览器,火狐浏览器,IE8+
var request = new XMLHttpRequest(); request.open('GET', '/my/url', true); request.onreadystatechange = function() { if (this.readyState === 4) { if (this.status >= 200 && this.status < 400) { // Success! var data = JSON.parse(this.responseText); } else { // Error :( } } }; request.send(); request = null;
谷歌浏览器,火狐浏览器,IE9+
var request = new XMLHttpRequest(); request.open('GET', '/my/url', true); request.onload = function() { if (request.status >= 200 && request.status < 400) { // Success! var data = JSON.parse(request.responseText); } else { // We reached our target server, but it returned an error } }; request.onerror = function() { // There was a connection error of some sort }; request.send();
谷歌浏览器,火狐浏览器,IE10+
var request = new XMLHttpRequest(); request.open('GET', '/my/url', true); request.onload = function() { if (this.status >= 200 && this.status < 400) { // Success! var data = JSON.parse(this.response); } else { // We reached our target server, but it returned an error } }; request.onerror = function() { // There was a connection error of some sort }; request.send();
>>>>Post
jQuery
$.ajax({ type: 'POST', url: '/my/url', data: data });
谷歌浏览器,火狐浏览器,IE8+
var request = new XMLHttpRequest(); request.open('POST', '/my/url', true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); request.send(data);
>>>>Request
jQuery
$.ajax({ type: 'GET', url: '/my/url', success: function(resp) { }, error: function() { } });
谷歌浏览器,火狐浏览器,IE8+
var request = new XMLHttpRequest(); request.open('GET', '/my/url', true); request.onreadystatechange = function() { if (this.readyState === 4) { if (this.status >= 200 && this.status < 400) { // Success! var resp = this.responseText; } else { // Error :( } } }; request.send(); request = null;
谷歌浏览器,火狐浏览器,IE9+
var request = new XMLHttpRequest(); request.open('GET', '/my/url', true); request.onload = function() { if (request.status >= 200 && request.status < 400) { // Success! var resp = request.responseText; } else { // We reached our target server, but it returned an error } }; request.onerror = function() { // There was a connection error of some sort }; request.send();
谷歌浏览器,火狐浏览器,IE10+
var request = new XMLHttpRequest(); request.open('GET', '/my/url', true); request.onload = function() { if (this.status >= 200 && this.status < 400) { // Success! var resp = this.response; } else { // We reached our target server, but it returned an error } }; request.onerror = function() { // There was a connection error of some sort }; request.send();