如何在 jQuery 的 load() 方法中捕获错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/753300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to catch error in jQuery's load() method
提问by cgp
I'm using jQuery's .load()
method to retrieve some data when a user clicks on a button.
.load()
当用户单击按钮时,我使用 jQuery 的方法来检索一些数据。
After the load successfully finishes, I show the result in a <div>
.
加载成功完成后,我将结果显示在<div>
.
The problem is, sometimes an error occurs in load()
while retrieving the data.
问题是,有时在load()
检索数据时会发生错误。
How can I catch an error in load()
?
我怎样才能捕捉到错误load()
?
回答by cgp
Just a little background on how a load error happens...
只是关于加载错误如何发生的一点背景......
$("body").load("/someotherpath/feedsx.pxhp", {limit: 25},
function (responseText, textStatus, req) {
if (textStatus == "error") {
return "oh noes!!!!";
}
});
Edit: Added a path other than the root path as requested by comments.
编辑:根据评论的要求添加了除根路径之外的路径。
回答by matt b
Besides passing a callback to the load() function as ólafur Waage suggests, you can also register "global" error handlers (global as in global for all ajax calls on the page).
除了像ólafur Waage 建议的那样将回调传递给load() 函数之外,您还可以注册“全局”错误处理程序(对于页面上的所有ajax 调用来说都是全局的)。
There are at least two ways to register global Ajax error handlers :
至少有两种方法可以注册全局 Ajax 错误处理程序:
Register just the error handler with ajaxError()
:
仅注册错误处理程序ajaxError()
:
$.ajaxError(function(event, request, settings) {
alert("Oops!!");
});
Or, use ajaxSetup()
to set up an error handler and other properties at the same time:
或者,用于ajaxSetup()
同时设置错误处理程序和其他属性:
$.ajaxSetup({
timeout: 5000,
error: function(event, request, settings){
alert("Oops!");
}
});
回答by ólafur Waage
load() offers a callback.
load() 提供回调。
Callback.
The function called when the ajax request is complete (not necessarily success).
打回来。
ajax请求完成时调用的函数(不一定成功)。
This is how its done IIRC. (haven't tested it)
这就是它如何完成 IIRC。(没测试过)
$("#feeds").load("feeds.php", {limit: 25},
function (responseText, textStatus, XMLHttpRequest) {
// XMLHttpRequest.responseText has the error info you want.
alert(XMLHttpRequest.responseText);
});
回答by vezult
Electric toolbox has an article called "Loading content with jQuery AJAX and dealing with failures"that appears to answer your question.
Electric 工具箱中有一篇名为“使用 jQuery AJAX 加载内容并处理失败”的文章似乎可以回答您的问题。
Apparently the callback function that you specify gets passed the response, status, and XmlHttpRequest object, allowing you to determine the status of your ajax request and handle the condition accordingly.
显然,您指定的回调函数会传递响应、状态和 XmlHttpRequest 对象,从而允许您确定 ajax 请求的状态并相应地处理条件。