promise wrap ajax

  • 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值