jQuery封裝非同步ajax
阿新 • • 發佈:2018-11-16
一、通過回撥方式:
function ajaxAsync(datas, callback) { var param = JSON.stringify(datas); $.ajax({ type: "POST", url: "www.********/rest", dataType: "json", data: { data: param }, beforeSend: function (request) { loading = layer.load(1, { shade: [0.3, "#fff"] }) }, success: function (re) { callback(re); }, error: function (re) { layer.msg('網路錯誤,稍後重試') }, complete: function (re) { layer.close(loading); } }); }
使用時:
ajaxAsync(datas, function (res) {
if (re.code == 1) {
console.log(res)
} else {
layer.msg(re.msg);
}
})
二、通過 $.Deferred (其實就是promise)
function reqAjax(param){ var deferred = $.Deferred(); $.ajax({ type:"post", dataType: 'json', url:"www.*****/rest", data: { data: JSON.stringify(param), }, success: function(data){ deferred.resolve(data) }, error: function(){ deferred.reject() } }); return deferred; }
使用時:
var defer = $.Deferred();
var def = reqAjax(param);
def.then(function(res){
defer.resolve(res);
});
def.fail(function(err){
defer.reject();
layer.msg("系統繁忙,請稍後再試!");
});