- ES6 Promise:
function ajax(method, url, data){
var xhr = new XMLHttpRequest();
return new Promise(function(resolve, reject){
xhr.onreadystatechange = function(){
if(xhr.readyState===4){
if(xhr.status === 200){
resolve(xhr.responseText);
}
}else{
reject(xhr.status);
}
};
xhr.open(method, url);
xhr.send(data);
});
}
ajax("GET",
"http://127.0.0.1:3004",
"ajaxData")
.then(function(text){console.log(text);})
.catch(function(status){console.log(status);});
- JQuery ajax:
jQuery在全局对象jQuery(也就是$)绑定了ajax()函数,可以处理AJAX请求。ajax(url, settings)函数需要接收一个URL和一个可选的settings对象,常用的选项如下:
async:是否异步执行AJAX请求,默认为true,千万不要指定为false;
method:发送的Method,缺省为’GET’,可指定为’POST’、’PUT’等;
contentType:发送POST请求的格式,默认值为’application/x-www-form-urlencoded; charset=UTF-8’,也可以指定为text/plain、application/json;
data:发送的数据,可以是字符串、数组或object。如果是GET请求,data将被转换成query附加到URL上,如果是POST请求,根据contentType把data序列化成合适的格式;
headers:发送的额外的HTTP头,必须是一个object;
dataType:接收的数据格式,可以指定为’html’、’xml’、’json’、’text’等,缺省情况下根据响应的Content-Type猜测。
var jqxhr = $.ajax('url', {
dataType: 'json'
}).done(function (data) {
alert('成功, 收到的数据: ' + JSON.stringify(data));
}).fail(function (xhr, status) {
alert('失败: ' + xhr.status + ', 原因: ' + status);
}).always(function () {
alert('请求完成: 无论成功或失败都会调用');
});
- Before ES6:
//constructor
var Promise = function() {
this.callbacks = [];
}
Promise.prototype = {
constructor: Promise,
resolve: function(result) {
this.complete("resolve", result);
},
reject: function(result) {
this.complete("reject", result);
},
complete: function(type, result) {
while (this.callbacks[0]) {
this.callbacks.shift()[type](result);
}
},
then: function(successHandler, failedHandler) {
this.callbacks.push({
resolve: successHandler,
reject: failedHandler
});
return this;
}
}
// test
var promise = new Promise();
var delay1 = function() {
setTimeout(function() {
promise.resolve('数据1');
}, 1000);
return promise;
};
var callback1 = function(re) {
re = re + '数据2';
console.log(re);
};
delay1().then(callback1)
参考:
http://www.cnblogs.com/fsjohnhuang/p/4135149.html
http://www.cnblogs.com/284628487a/p/5556144.html