国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > AJAX > 正文

用Promise解決多個異步Ajax請求導致的代碼嵌套問題(完美解決方案

2024-09-01 08:27:25
字體:
來源:轉載
供稿:網友

問題

前端小同學在做頁面的時候,犯了個常見的錯誤:把多個Ajax請求順序著寫下來了,而后面的請求,對前面請求的返回結果,是有依賴的。如下面的代碼所示:

var someData;$.ajax({      url: '/prefix/entity1/action1',      type: 'GET' ,      async: true,      contentType: "application/json",      success: function (resp) {        //do something on response        someData.attr1 = resp.attr1;      },      error: function (XMLHttpRequest, textStatus, errorThrown) {        //在這個頁面里,所有的請求的錯誤都做同樣的處理        if (XMLHttpRequest.status == "401") {          window.location.href = '/login.html';        } else {          alert(XMLHttpRequest.responseText);        }      }    });$.ajax({      url: '/prefix/entity2/action2',      type: 'POST' ,      dataType: "json",      data: JSON.stringify(someData),      async: true,      contentType: "application/json",      success: function (resp) {        //do something on response       },      error: function (XMLHttpRequest, textStatus, errorThrown) {        //在這個頁面里,所有的請求的錯誤都做同樣的處理        if (XMLHttpRequest.status == "401") {          window.location.href = '/login.html';        } else {          alert(XMLHttpRequest.responseText);        }      }    });

以上代碼有兩個問題:

*首先就是執行順序不能保證,action2很可能在action1返回之前就發出了,導致someData.attr1這個參數沒能正確傳出

*其次兩個ajax請求的代碼重復很嚴重

思路

代碼重復的問題相對好解決,尤其是在自己的項目里,各種參數可以通過規范定死,封裝一個參數更少的ajax方法就好了
//url:地址//data:數據對象,在函數內部會轉化成json串,如果沒傳,表示用GET方法,如果傳了,表示用POST方法function ajax(url, data, callback) {    $.ajax({      url: url,      type: data == null ? 'GET' : 'POST',      dataType: "json",      data: data == null ? '' : JSON.stringify(data),      async: true,      contentType: "application/json",      success: function (resp) {        callback(resp);      },      error: function (XMLHttpRequest, textStatus, errorThrown) {        if (XMLHttpRequest.status == "401") {          window.parent.location = '/enterprise/enterprise_login.html';          self.location = '/enterprise/enterprise_login.html';        } else {          alert(XMLHttpRequest.responseText);        }      }    });}

這樣只有url,data和callback三個必要的參數要填,其他都定死了

執行順序的問題,可以把第二個請求放在第一個請求的回調里,形如:
ajax('/prefix/entity1/action1',null, function(resp){   //do something on response   someData.attr1 = resp.attr1;   ajax('/prefix/entity2/action2', someData, function(resp){     //do something on response   }};            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 托里县| 宝兴县| 金溪县| 吉安县| 涡阳县| 辽宁省| 德阳市| 东港市| 大宁县| 磐石市| 五台县| 鄱阳县| 湟中县| 清涧县| 京山县| 广丰县| 永年县| 合江县| 疏勒县| 恩施市| 延庆县| 上思县| 仙游县| 哈尔滨市| 广西| 临澧县| 石屏县| 阜城县| 房产| 云霄县| 饶平县| 都匀市| 玉林市| 莒南县| 丽江市| 辽阳县| 莱西市| 通城县| 柳州市| 陆丰市| 桃源县|