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方法
});