問題
前端小同學在做頁面的時候,犯了個常見的錯誤:把多個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 }};
新聞熱點
疑難解答
圖片精選