我正在使用JQuery $ .ajax遍歷一組JSON URL並將結果下載到數組中。一些URL返回404 - 我正在處理&顯示爲div消息。將變量傳遞給jQuery ajax成功或錯誤函數
但是,我似乎無法通過URL,更確切地說,它總是隻傳遞數組中的最後一個URL。
我認爲這是因爲AJAX是異步的,需要更長的時間來完成,但我不知道怎麼回事,以確保只有當前JSON的URL(或變量)正在顯示成功或錯誤的
我的代碼:
// For every URL loop through 'baseitems' array
for (var i = 0; i < baseitems.length; i++) {
// This is where I'm hoping to store the current URL as a variable to pass to the end-user on Success or Error
var caturl = baseURL + "/" + baseitems[i];
// Get the data via JSON
$.ajax({
type: "GET",
url: caturl,
dataType: "json",
async: true, // set so that the variables caturl get updated below
success: function (result) {
// Success: store the object into catalog array
cat.unshift(result);
$('#showdata').prepend("Loaded: " + caturl + "</br>"); // still buggy here - probably async JSON issue
},
error: function (xhr, textStatus, error) {
// Error: write out error
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
$('#showdata').prepend("ERROR : '" + error + "' trying to access: " + caturl + "</br>"); // still buggy here - probably async JSON issue
}
});
}
**更新:工作代碼**
與@charlietfl幫助+一些很好的事情完成的工作代碼就像下面的成功/錯誤代碼+加載的URL的數量一樣。感謝charlietfl &調解人!
$.ajax({
type: "GET",
url: caturl,
dataType: "json",
async: true, // set so that the variables caturl get updated below
beforeSend: function (jqXHR, settings) {
/* add url property and get value from settings (or from caturl)*/
jqXHR.url = settings.url;
},
success: function (result, textStatus, jqXHR) {
// Success: store the object into catalog array
var url = jqXHR.url;
cat.unshift(result);
$('#showdata').prepend("<font size=\"1\">Loading: " + url + " status: " + textStatus + "</font></br>");
successcount += 1;
},
/* error to be deprecated in jQuery 1.8 , superseded by "fail" */
error: function (jqXHR, textStatus, error) {
var url = jqXHR.url;
/* replace caturl with url in your append */
$('#showdata').prepend("<font size=\"1\" color=\"red\">ERROR : '" + error + "' trying to access: " + url + "</font></br>");
},
complete: function (jqXHR, textStatus) {
$('#showdata').prepend("<font size=\"3\">Loaded <b>" + successcount + "</b> of " + baseitems.length + " total catalogs.</font></br>")
}
});
您是否曾嘗試在caturl的ajax調用中將'caturl'的值傳遞給函數,然後將結果傳遞回來? 或者,因爲你已經知道服務器的URL,你通過它回到了阿賈克斯成功'result'並使用它有 – peacemaker