如何把ajax改成同步请求,ajax同步请求改成异步请求,如何拿到返回数据插入dom之中?... |
您所在的位置:网站首页 › ajax怎么改成同步 › 如何把ajax改成同步请求,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,resulssage) } }, //全局配置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 = '请选择项目类型'; $.each(res.result, function (k, v) { selecthtml += '' + v.name + ""; }); $("#status").html(selecthtml); $("#state").html(selecthtml); } 一旦 async 改成 true |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |