本文介绍了使用JSONP时,如何捕获jQuery $ .getJSON(或数据类型设置为'jsonp'的$ .ajax)错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery中使用JSONP时是否可以捕获错误?我已经尝试了$ .getJSON和$ .ajax方法,但都没有捕获我正在测试的404错误。这是我尝试过的(请记住,这些都能成功运行,但我想在失败的情况下处理):

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");
    }
});

还有:

jQuery.getJSON(handlerURL + "&callback=?",
    function(jsonResult){
        alert("Success!");
    });

我也尝试添加$ .ajaxError,但这也不起作用:

I've also tried adding the $.ajaxError but that didn't work either:

jQuery(document).ajaxError(function(event, request, settings){
   alert("Error");
});

提前感谢您的回复!

推荐答案

似乎没有返回成功结果的JSONP请求永远不会触发任何事件,成功或失败,无论是好是坏还是显而易见的设计。

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.

搜索他们的bug追踪器之后,有这可能是使用超时回调的可能解决方案。请参阅。如果您无法捕获错误,您可以在等待合理的时间成功后至少超时。

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时,如何捕获jQuery $ .getJSON(或数据类型设置为'jsonp'的$ .ajax)错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 01:03