ajax中的一些寫法珍藏

1、第一種寫法:
ajax1();
function ajax1(){
$.ajax({
url: '‘’,
type: ‘get’,
data: “”,
async: true,//默認是異步
dataType: ‘json’,
beforeSend: function () {},
success: function (json) {
if(json.status != 1) {
return false;
}
console.log(“ajax1的方法:”+JSON.stringify(json.data[0].gindex));
},
error: function (err) {
console.log(err)
},
complete: function (msg) {}

        });

}

2、第二種寫法:
ajax2();
function ajax2(){
$.ajax({
url: “”,
type: ‘get’,
data: “”,
async: true,//默認是異步
dataType: ‘json’,
beforeSend: function() {}
}).done(function(json){
console.log(“請求成功:”+JSON.stringify(json.data[0].gindex)); //相當於sucess
}).fail(function(err){
console.log(“請求失敗”+err); //相當於error方法
}).always(function(msg){
console.log(“請求完成”); //相當於complete方法
});
}

3、第三種寫法

var ajaxPromise=()=> {
return new Promise((resovle, reject) => {
$.ajax({
url: “”,
type: ‘get’,
data: “”,
async: true,//默認是異步
dataType: ‘json’,
beforeSend: function () {},
success: function (json) {
resovle(json);
},
error: function (err) {
reject(err);
},
complete: function (msg) {}

    });
})

}

3-1、注意 --如果then方法中第一個函數相當於sucess, 第二個函數相當於error,如果第二個函數沒有寫,那麼就會執行catch的方法執行的數據。如果第二個函數寫了,那不會執行catch方法。
ajaxPromise().then(json => {
console.log(“請求成功:”+JSON.stringify(json.data[0].gindex)); //相當於sucess返回的數據
},err=>{
console.log(“請求失敗”+err); //相當於error方法返回的數據提示
})

3-2、
ajaxPromise().then(json => {
console.log(“請求成功:”+JSON.stringify(json.data[0].gindex)); //相當於sucess返回的數據
}).catch(err => {
console.log(“請求失敗”+err); //相當於error方法
});

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章