在Ajax中优雅地处理404
Gracefully handling 404 in Ajax
我使用XmlHttpObject
从服务器获取一堆文件。这些文件对我的应用程序并不重要,所以如果其中任何一个丢失,我只想记录错误并继续。问题是,每当没有找到文件时,就会引发异常,并破坏之后的所有代码。
function loadFile(path) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.status == 404) {
// I can live with that, log it and go on
console.log("file missing");
return;
}
if (xhr.readyState == 4) {
// Wohoo, all is fine, do loading stuff
}
}
xhr.open("GET", path, true);
xhr.send();
}
// Some time after
for (var i in files) {
loadFile(file[i]);
// If a file is not found, an exception is raised and the code below doesnt execute
}
// More stuff
我怎么做才能得到这种行为?
您可能想要做的是传递一个函数,该函数应该在文件加载时调用。正如Tys指出的,你应该在检查状态之前检查readystate:
function loadFile(path, onsuccess, onnotfound) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 404) {
// Do error handling when request is complete
onnotfound(xhr);
return;
}
// Wohoo, all is fine, do loading stuff
onsuccess(xhr);
}
}
xhr.open("GET", path, true);
xhr.send();
}
// Some time after
for (var i in files) {
loadFile(file[i], function(xhr) {
// Stuff to process a successfull response
// Adding things to the DOM etc etc. based on the response
},
function(xhr) {
console.log("file missing");
// Additional error handling on file missing
});
}
你的积木顺序不对。只检查xhr。状态时xhr。readyState已更改为4。您过早地检查了状态。
function loadFile(path) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 404) {
// I can live with that, log it and go on
console.log("file missing");
}
else {
// Wohoo, all is fine, do loading stuff
}
}
}
xhr.open("GET", path, true);
xhr.send();
}
// Some time after
for (var i in files) {
loadFile(file[i]);
// If a file is not found, an exception is raised and the code below doesnt execute
}
// More stuff
如果你在chrome中编程,唯一的方法是通过在控制台中禁用此消息来修复它。根据Chromium团队的说法,这是一个特性,而不是一个bug。图。检查火狐中是否出现错误,如果没有,可能是这样。
相关文章:
- 如何处理Ajax.BeginForm()OnError OnFailure回调
- Masony无法处理ajax响应
- 如何在phonegap应用程序中处理Ajax json响应
- 在嵌套循环中处理 AJAX (Angularjs)
- 运行 AJAX 需要什么 - 将 jQuery 添加到页面处理 AJAX 调用
- 在 Rails 中处理 ajax 请求
- 为什么不允许在jquery数据表服务器端处理ajax中使用成功
- JQuery无法处理ajax返回的内容
- 处理AJAX回调
- 难以处理ajax调用
- 额外的层可以更好地处理ajax调用
- 如何在响应时处理ajax错误
- DROPZONE - 在 fle 上传期间处理 AJAX 请求中的会话超时
- 在快递中.js有没有办法同时处理 ajax 表单提交和浏览器帖子提交
- 动态处理 ajax 结果
- 如何在没有jQuery的情况下处理Ajax浏览器兼容性
- CakePHP - 处理 ajax 调用中的 url
- 当服务器没有响应时如何处理 ajax 调用
- 全局和特定错误处理 AJAX jQuery
- 处理 AJAX 调用的 Web 工作人员 - 优化矫枉过正