封装jq的ajax

function getData(url,ops,func){
    type = "get";
    url = apiurl + url;
    $.ajax({
       type: type,
       url:url ,
       dataType: "json",
       data: ops,
       error: function (err) {
           //请求失败时被调用的函数 
           console.log("失败:" + err);
       },
       success: function (res) {
            func(res)
       }
   });
}

调用

getData(getMerSupCount,{},function(res){
            $(".head .num01").html(res.data.merCount);
            $(".head .num02").html(res.data.supCount);
        })

 es6 promise封装方法

function Getdata(url,ops,type){ //默认get
    url = apiurl + url; //线上http:
    // url = 'http://192.168.2.101:7001/'+url;//线下
    var promiseObj = new Promise(function(resolve, reject) {
        $.ajax({
            type:type,
            url:url,
            data: ops,
            async: false,
            dataTyp: "json",
            headers: {
                "client-token": "PC"
            },
            success: res =>{
                resolve(res);
            },
            error: res => {
                reject(res);
            }
        })
    })
    return promiseObj;
}

调用

Getdata(busList, {
            type: 2, //商户类型(  1正常商户 2热门商户 3黑商户 -1查全部)
            size: 20, //每页条数
            current: 1 //页码
        }).then(res => {
            console.log(res)
            let item = "";

            $.each(res.data.records, function (index, val) {
                item += `<div class="item">
                            <img src="${val.imgPath}" class="img-responsive" alt="">
                            <div class="mask"><a href="platDetail.html?id=${val.id}">${val.name}</a></div>
                        </div>`;
            })
            $("#hot-plat").html(item);



        })

以上就是接口封装的方法,如有问题,请留言指教。

posted @ 2019-11-22 16:43  小丶鱼  阅读(236)  评论(0编辑  收藏  举报