我正在使用 JQuery $.ajax 遍历一组 JSON URL 并将结果下载到一个数组中。一些 URL 返回 404 - 我正在处理并显示为 div 消息。
但是,我似乎无法传递 URL,更准确地说,它总是只传递数组中的最后一个 URL。
我认为这是因为 ajax 是异步的并且需要更长的时间才能完成,但我不确定如何确保只有当前的 JSON url(或变量)显示在 SUCCESS 或 ERROR 上
我的代码:
// 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>")
}
});