ajax同步请求改成异步请求,如何拿到返回数据插入dom之中?

历史遗留项目,前人封装了一个全局的ajax请求,这个项目所有的请求都用的这个方法,发现所有的请求同时同步的,页面卡顿,但是改成异步之后,请求的数据就报错Null,请教该如何优化

封装的ajax请求

    AjaxRequest: function (url, data, type) {
        var reresult = null;
        var loading = $('body').loading();
        var loadingCount = 0;//loading计数器
        $.ajax({
            type: type == undefined ? 'GET' : type,
            dataType: "json", //返回数据类型  
            data: data != null ? data : {},
            headers: {
                'token': localStorage.getItem("token"),
                'type': localStorage.getItem("RequestHeadType")
            },
            async: false,//都是同步请求,这里改成true 就报错
            contentType: 'application/json',
            url: comfun.ComIp.serviceIp + url,
            beforeSend: function () {
                loading.show();
                loadingCount++;
                console.log(111,loadingCount)
            },
            success: function (result) { //请求成功后处理函数。  取到Json对象data 
                if (result.success) {
                    reresult = result
                } else {
                    reresult = result
                    // comfun.ErrorPage(result.code,result.message)
                }
            },
            //全局配置token处理
            complete: function (XMLHttpRequest, textStatus) {
                var res = XMLHttpRequest.responseText;
                loadingCount--
                if (loadingCount == 0) {
                    loading.hide();
                }
                try {
                    var jsonData = JSON.parse(res);
                    if (jsonData.code == 401) {
                        //如果超时就处理 ,指定要跳转的页面(比如登陆页)
                        setTimeout(function () {
                            window.location.href = "/Login.html";
                        }, 500);
                    }
                } catch (e) { }
            },
            error: function () { //请求失败处理函数     
                comfun.ErrorPage(404)
                // alert("网络异常请稍后重试")
            }
        })
        return reresult
    },

具体页面使用的实例 项目中几乎所有的请求都是这么写的 只是一个实例

function getStatus() {
    var res = window.comfun.AjaxRequest("url", JSON.stringify({
        type: "2"
    }), "POST");
    var selecthtml = '';
    selecthtml = '<option value="">请选择项目类型</option>';
    $.each(res.result, function (k, v) {
        selecthtml +=
            '<option value="' + v.id + '">' + v.name + "</option>";
    });
    $("#status").html(selecthtml);
    $("#state").html(selecthtml);
}

一旦 async 改成 true

image.png

阅读 1.9k
2 个回答

没办法,写法都完全不一样,异步方法哪还有返回值了,该要么 Promise 要么用回调函数了。

这种情况应该老方法就不去动它,另写一个异步的新方法,然后把外部调用都一个一个改成去调新方法,不可能是简简单单只改一下老方法就成了的。

解决方案

这个方法改一下
`

AjaxRequest: function (url, data, type) {
 return new Promise((resolve, reject) => {
    var loading = $('body').loading();
    var loadingCount = 0;//loading计数器
    $.ajax({
        type: type == undefined ? 'GET' : type,
        dataType: "json", //返回数据类型  
        data: data != null ? data : {},
        headers: {
            'token': localStorage.getItem("token"),
            'type': localStorage.getItem("RequestHeadType")
        },
        // 写成异步的请求
        async: true,//都是同步请求,这里改成true 就报错
        contentType: 'application/json',
        url: comfun.ComIp.serviceIp + url,
        beforeSend: function () {
            loading.show();
            loadingCount++;
            console.log(111,loadingCount)
        },
        success: function (result) { //请求成功后处理函数。  取到Json对象data 
            if (result.success) {
                resolve(result)
            } else {
                reresult = result
                // comfun.ErrorPage(result.code,result.message)
            }
        },
        //全局配置token处理
        complete: function (XMLHttpRequest, textStatus) {
            var res = XMLHttpRequest.responseText;
            loadingCount--
            if (loadingCount == 0) {
                loading.hide();
            }
            try {
                var jsonData = JSON.parse(res);
                if (jsonData.code == 401) {
                    //如果超时就处理 ,指定要跳转的页面(比如登陆页)
                    setTimeout(function () {
                        window.location.href = "/Login.html";
                    }, 500);
                }
            } catch (e) { }
        },
        error: function () { //请求失败处理函数     
            comfun.ErrorPage(404)
            // alert("网络异常请稍后重试")
        }
    })
    });
},

`

调用的地方这么写

`
async function getStatus() {

var res = await window.comfun.AjaxRequest("url", JSON.stringify({
    type: "2"
}), "POST");
var selecthtml = '';
selecthtml = '<option value="">请选择项目类型</option>';
$.each(res.result, function (k, v) {
    selecthtml +=
        '<option value="' + v.id + '">' + v.name + "</option>";
});
$("#status").html(selecthtml);
$("#state").html(selecthtml);

}
`

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题