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方法
    });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值