使用 JSONP 时如何捕获 jQuery $.getJSON(或数据类型设置为“jsonp”的 $.ajax)错误?
在 jQuery 中使用 JSONP 时是否可以捕获错误? 我已经尝试了 $.getJSON 和 $.ajax 方法,但都无法捕获我正在测试的 404 错误。 这是我尝试过的(请记住,这些都成功工作,但我想在失败时处理这种情况):
jQuery.ajax({
type: "GET",
url: handlerURL,
dataType: "jsonp",
success: function(results){
alert("Success!");
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Error");
}
});
而且:
jQuery.getJSON(handlerURL + "&callback=?",
function(jsonResult){
alert("Success!");
});
我还尝试添加 $.ajaxError 但这也不起作用:
jQuery(document).ajaxError(function(event, request, settings){
alert("Error");
});
Is it possible to catch an error when using JSONP with jQuery? I've tried both the $.getJSON and $.ajax methods but neither will catch the 404 error I'm testing. Here is what I've tried (keep in mind that these all work successfully, but I want to handle the case when it fails):
jQuery.ajax({
type: "GET",
url: handlerURL,
dataType: "jsonp",
success: function(results){
alert("Success!");
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Error");
}
});
And also:
jQuery.getJSON(handlerURL + "&callback=?",
function(jsonResult){
alert("Success!");
});
I've also tried adding the $.ajaxError but that didn't work either:
jQuery(document).ajaxError(function(event, request, settings){
alert("Error");
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
这是我对类似问题的详细回答。
这是代码:
Here's my extensive answer to a similar question.
Here's the code:
似乎不返回成功结果的 JSONP 请求永远不会触发任何事件,无论成功还是失败,无论好坏,这显然都是设计使然。
搜索他们的错误跟踪器后,有补丁这可能是一个可能的解决方案使用超时回调。 请参阅错误报告#3442。 如果您无法捕获错误,您至少可以在等待一段合理的时间以获取成功后超时。
It seems that JSONP requests that don't return a successful result never trigger any event, success or failure, and for better or worse that's apparently by design.
After searching their bug tracker, there's a patch which may be a possible solution using a timeout callback. See bug report #3442. If you can't capture the error, you can at least timeout after waiting a reasonable amount of time for success.
检测 JSONP 问题
如果您不想下载依赖项,您可以自行检测错误状态。 这很容易。
您只能通过使用某种超时来检测 JSONP 错误。 如果在特定时间内没有有效响应,则假设发生错误。 不过,该错误基本上可以是任何内容。
这是检查错误的简单方法。 只需使用
success
标志:正如 thedawnrider 在评论中提到的,您也可以使用clearTimeout 代替:
为什么? 继续阅读...
简而言之,JSONP 的工作原理如下:
JSONP 不像常规 AJAX 请求那样使用 XMLHttpRequest。 相反,它会在页面中注入
标记,其中“src”属性是请求的 URL。 响应的内容封装在 JavaScript 函数中,然后在下载时执行该函数。
例如。
JSONP 请求:
https://api.site.com/endpoint?this=that&callback=myFunc
Javascript 会将此脚本标签注入到 DOM 中:
什么当
标签添加到 DOM 时会发生什么? 显然,它被执行了。
因此,假设对此查询的响应产生了一个 JSON 结果,如下所示:
对于浏览器来说,这与脚本的源代码相同,因此它会被执行。 但是当你执行这个时会发生什么:
嗯,什么也没有。 它只是一个物体。 它不会被存储、保存,也不会发生任何事情。
这就是 JSONP 请求将其结果包装在函数中的原因。 必须支持 JSONP 序列化的服务器会看到您指定的回调参数,并返回以下内容: 然后
执行以下内容:
... 这更有用。 在本例中,代码中的某个位置有一个名为
myFunc
的全局函数:就是这样。 这就是 JSONP 的“魔力”。 然后构建超时检查非常简单,如上所示。 发出请求后立即开始超时。 X 秒后,如果您的标志仍未设置,则请求超时。
Detecting JSONP problems
If you don't want to download a dependency, you can detect the error state yourself. It's easy.
You will only be able to detect JSONP errors by using some sort of timeout. If there's no valid response in a certain time, then assume an error. The error could be basically anything, though.
Here's a simple way to go about checking for errors. Just use a
success
flag:As thedawnrider mentioned in comments, you could also use clearTimeout instead:
Why? Read on...
Here's how JSONP works in a nutshell:
JSONP doesn't use XMLHttpRequest like regular AJAX requests. Instead, it injects a
<script>
tag into the page, where the "src" attribute is the URL of the request. The content of the response is wrapped in a Javascript function which is then executed when downloaded.For example.
JSONP request:
https://api.site.com/endpoint?this=that&callback=myFunc
Javascript will inject this script tag into the DOM:
What happens when a
<script>
tag is added to the DOM? Obviously, it gets executed.So suppose the response to this query yielded a JSON result like:
To the browser, that's the same thing as a script's source, so it gets executed. But what happens when you execute this:
Well, nothing. It's just an object. It doesn't get stored, saved, and nothing happens.
This is why JSONP requests wrap their results in a function. The server, which must support JSONP serialization, sees the
callback
parameter you specified, and returns this instead:Then this gets executed instead:
... which is much more useful. Somewhere in your code is, in this case, a global function called
myFunc
:That's it. That's the "magic" of JSONP. Then to build in a timeout check is very simple, like shown above. Make the request and immediately after, start a timeout. After X seconds, if your flag still hasn't been set, then the request timed out.
我知道这个问题有点老了,但我没有看到给出问题的简单解决方案的答案,所以我想我会分享我的“简单”解决方案。
我们可以简单地使用
.fail()
回调来检查是否发生错误。希望这可以帮助 :)
I know this question is a little old but I didn't see an answer that gives a simple solution to the problem so I figured I would share my 'simple' solution.
We can simply use the
.fail()
callback to check to see if an error occurred.Hope this helps :)
如果您与提供商合作,您可以发送另一个查询字符串参数作为出现错误时要回调的函数。
?回调=?&错误=?
这称为 JSONPE,但它根本不是事实上的标准。
然后,提供程序将信息传递给错误函数以帮助您进行诊断。
但对解决通讯错误没有帮助 - jQuery 必须更新才能在超时时回调错误函数,如 Adam Bellaire 的回答所示。
If you collaborate with the provider, you could send another query string parameter being the function to callback when there's an error.
?callback=?&error=?
This is called JSONPE but it's not at all a defacto standard.
The provider then passes information to the error function to help you diagnose.
Doesn't help with comm errors though - jQuery would have to be updated to also callback the error function on timeout, as in Adam Bellaire's answer.
看起来现在正在工作:
Seems like this is working now:
我用它来捕获 JSON 错误
编辑:或者您也可以获得错误消息。 这会让您知道错误到底是什么。 在 catch 块中尝试以下语法
I use this to catch an JSON error
Edit: Alternatively you can get the error message also. This will let you know what the error is exactly. Try following syntax in catch block
也许这有效?
我不知道状态何时进入“错误”模式。 但我用 404 测试过,它有响应
Mayby this works?
I dont know whenever the status goes in "error" mode. But i tested it with 404 and it responded
您可以通过在 ajax 请求中添加此属性来显式处理任何错误号:
因此,您的代码应该如下所示:
希望这对您有帮助:)
you ca explicitly handle any error number by adding this attribute in the ajax request:
so, your code should be like this:
hope this helps you :)
我还在 stackoverflow - 错误处理中发布了这个答案在 getJSON 调用中
我知道自从有人在这里回答以来已经有一段时间了,并且发布者可能已经从这里或其他地方得到了他的答案。 不过,我确实认为这篇文章将帮助任何人在执行 getJSON 请求时寻找一种方法来跟踪错误和超时。 因此,下面我对问题的回答
getJSON 结构如下(在 http://api.jqueri.com):
实现它
大多数人使用 url var 提供链接的地方来 对于 JSON 数据,datatosend 作为添加
"?callback=?"
和其他变量的位置,必须发送这些变量才能返回正确的 JSON 数据,而 success 函数作为以下函数处理数据。但是,您可以在成功函数中添加 status 和 xhr 变量。 status 变量包含以下字符串之一:“success”、“notmodified”、“error”、“timeout”或“parsererror”,xhr 变量包含返回的 XMLHttpRequest 对象
(在w3schools上找到)
这样就很简单跟踪超时和错误,而无需实现请求完成后启动的自定义超时跟踪器。
希望这对仍在寻找该问题答案的人有所帮助。
I also posted this answer in stackoverflow - Error handling in getJSON calls
I know it's been a while since someone answerd here and the poster probably already got his answer either from here or from somewhere else. I do however think that this post will help anyone looking for a way to keep track of errors and timeouts while doing getJSON requests. Therefore below my answer to the question
The getJSON structure is as follows (found on http://api.jqueri.com):
most people implement that using
where they use the url var to provide a link to the JSON data, the datatosend as a place to add the
"?callback=?"
and other variables that have to be send to get the correct JSON data returned, and the success funcion as a function for processing the data.You can however add the status and xhr variables in your success function. The status variable contains one of the following strings : "success", "notmodified", "error", "timeout", or "parsererror", and the xhr variable contains the returned XMLHttpRequest object
(found on w3schools)
This way it is easy to keep track of timeouts and errors without having to implement a custom timeout tracker that is started once a request is done.
Hope this helps someone still looking for an answer to this question.