使用 JSONP 时如何捕获 jQuery $.getJSON(或数据类型设置为“jsonp”的 $.ajax)错误?

发布于 2024-07-08 23:15:09 字数 679 浏览 4 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

相对绾红妆 2024-07-15 23:15:09

这是我对类似问题的详细回答。

这是代码:

jQuery.getJSON(handlerURL + "&callback=?", 
    function(jsonResult){
        alert("Success!");
    })
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); })
.always(function() { alert('getJSON request ended!'); });

Here's my extensive answer to a similar question.

Here's the code:

jQuery.getJSON(handlerURL + "&callback=?", 
    function(jsonResult){
        alert("Success!");
    })
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); })
.always(function() { alert('getJSON request ended!'); });
撞了怀 2024-07-15 23:15:09

似乎不返回成功结果的 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.

决绝 2024-07-15 23:15:09

检测 JSONP 问题

如果您不想下载依赖项,您可以自行检测错误状态。 这很容易。

您只能通过使用某种超时来检测 JSONP 错误。 如果在特定时间内没有有效响应,则假设发生错误。 不过,该错误基本上可以是任何内容。

这是检查错误的简单方法。 只需使用 success 标志:

var success = false;

$.getJSON(url, function(json) {
    success = true;
    // ... whatever else your callback needs to do ...
});

// Set a 5-second (or however long you want) timeout to check for errors
setTimeout(function() {
    if (!success)
    {
        // Handle error accordingly
        alert("Houston, we have a problem.");
    }
}, 5000);

正如 thedawnrider 在评论中提到的,您也可以使用clearTimeout 代替:

var errorTimeout = setTimeout(function() {
    if (!success)
    {
        // Handle error accordingly
        alert("Houston, we have a problem.");
    }
}, 5000);

$.getJSON(url, function(json) {
    clearTimeout(errorTimeout);
    // ... whatever else your callback needs to do ...
});

为什么? 继续阅读...


简而言之,JSONP 的工作原理如下:

JSONP 不像常规 AJAX 请求那样使用 XMLHttpRequest。 相反,它会在页面中注入

例如。

JSONP 请求:https://api.site.com/endpoint?this=that&callback=myFunc

Javascript 会将此脚本标签注入到 DOM 中:

<script src="https://api.site.com/endpoint?this=that&callback=myFunc"></script>

什么当

因此,假设对此查询的响应产生了一个 JSON 结果,如下所示:

{"answer":42}

对于浏览器来说,这与脚本的源代码相同,因此它会被执行。 但是当你执行这个时会发生什么:

<script>{"answer":42}</script>

嗯,什么也没有。 它只是一个物体。 它不会被存储、保存,也不会发生任何事情。

这就是 JSONP 请求将其结果包装在函数中的原因。 必须支持 JSONP 序列化的服务器会看到您指定的回调参数,并返回以下内容: 然后

myFunc({"answer":42})

执行以下内容:

<script>myFunc({"answer":42})</script>

... 这更有用。 在本例中,代码中的某个位置有一个名为 myFunc 的全局函数:

myFunc(data)
{
    alert("The answer to life, the universe, and everything is: " + data.answer);
}

就是这样。 这就是 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:

var success = false;

$.getJSON(url, function(json) {
    success = true;
    // ... whatever else your callback needs to do ...
});

// Set a 5-second (or however long you want) timeout to check for errors
setTimeout(function() {
    if (!success)
    {
        // Handle error accordingly
        alert("Houston, we have a problem.");
    }
}, 5000);

As thedawnrider mentioned in comments, you could also use clearTimeout instead:

var errorTimeout = setTimeout(function() {
    if (!success)
    {
        // Handle error accordingly
        alert("Houston, we have a problem.");
    }
}, 5000);

$.getJSON(url, function(json) {
    clearTimeout(errorTimeout);
    // ... whatever else your callback needs to do ...
});

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:

<script src="https://api.site.com/endpoint?this=that&callback=myFunc"></script>

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:

{"answer":42}

To the browser, that's the same thing as a script's source, so it gets executed. But what happens when you execute this:

<script>{"answer":42}</script>

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:

myFunc({"answer":42})

Then this gets executed instead:

<script>myFunc({"answer":42})</script>

... which is much more useful. Somewhere in your code is, in this case, a global function called myFunc:

myFunc(data)
{
    alert("The answer to life, the universe, and everything is: " + data.answer);
}

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.

一桥轻雨一伞开 2024-07-15 23:15:09

我知道这个问题有点老了,但我没有看到给出问题的简单解决方案的答案,所以我想我会分享我的“简单”解决方案。

$.getJSON("example.json", function() {
      console.log( "success" );
}).fail(function() { 
      console.log( "error" ); 
}); 

我们可以简单地使用 .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.

$.getJSON("example.json", function() {
      console.log( "success" );
}).fail(function() { 
      console.log( "error" ); 
}); 

We can simply use the .fail() callback to check to see if an error occurred.

Hope this helps :)

若相惜即相离 2024-07-15 23:15:09

如果您与提供商合作,您可以发送另一个查询字符串参数作为出现错误时要回调的函数。

?回调=?&错误=?

这称为 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.

你是年少的欢喜 2024-07-15 23:15:09

看起来现在正在工作:

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

Seems like this is working now:

jQuery(document).ajaxError(function(event, request, settings){
   alert("Error");
});
2024-07-15 23:15:09

我用它来捕获 JSON 错误

try {
   $.getJSON(ajaxURL,callback).ajaxError();
} catch(err) {
   alert("wow");
   alert("Error : "+ err);
}

编辑:或者您也可以获得错误消息。 这会让您知道错误到底是什么。 在 catch 块中尝试以下语法

alert("Error : " + err);

I use this to catch an JSON error

try {
   $.getJSON(ajaxURL,callback).ajaxError();
} catch(err) {
   alert("wow");
   alert("Error : "+ err);
}

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

alert("Error : " + err);
初懵 2024-07-15 23:15:09

也许这有效?

.complete(function(response, status) {
    if (response.status == "404")
        alert("404 Error");
    else{
        //Do something
    }   
    if(status == "error")
        alert("Error");
    else{
        //Do something
    }
});

我不知道状态何时进入“错误”模式。 但我用 404 测试过,它有响应

Mayby this works?

.complete(function(response, status) {
    if (response.status == "404")
        alert("404 Error");
    else{
        //Do something
    }   
    if(status == "error")
        alert("Error");
    else{
        //Do something
    }
});

I dont know whenever the status goes in "error" mode. But i tested it with 404 and it responded

隔纱相望 2024-07-15 23:15:09

您可以通过在 ajax 请求中添加此属性来显式处理任何错误号:

statusCode: {
        404: function() {
          alert("page not found");
        }
    }

因此,您的代码应该如下所示:

jQuery.ajax({
type: "GET",
statusCode: {
        404: function() {
          alert("page not found");
        }
},
url: handlerURL,
dataType: "jsonp",
success: function(results){
    alert("Success!");
},
error: function(XMLHttpRequest, textStatus, errorThrown){
    alert("Error");
}
});

希望这对您有帮助:)

you ca explicitly handle any error number by adding this attribute in the ajax request:

statusCode: {
        404: function() {
          alert("page not found");
        }
    }

so, your code should be like this:

jQuery.ajax({
type: "GET",
statusCode: {
        404: function() {
          alert("page not found");
        }
},
url: handlerURL,
dataType: "jsonp",
success: function(results){
    alert("Success!");
},
error: function(XMLHttpRequest, textStatus, errorThrown){
    alert("Error");
}
});

hope this helps you :)

是伱的 2024-07-15 23:15:09

我还在 stackoverflow - 错误处理中发布了这个答案在 getJSON 调用中

我知道自从有人在这里回答以来已经有一段时间了,并且发布者可能已经从这里或其他地方得到了他的答案。 不过,我确实认为这篇文章将帮助任何人在执行 getJSON 请求时寻找一种方法来跟踪错误和超时。 因此,下面我对问题的回答

getJSON 结构如下(在 http://api.jqueri.com):

$(selector).getJSON(url,data,success(data,status,xhr))

实现它

$.getJSON(url, datatosend, function(data){
    //do something with the data
});

大多数人使用 url var 提供链接的地方来 对于 JSON 数据,datatosend 作为添加 "?callback=?" 和其他变量的位置,必须发送这些变量才能返回正确的 JSON 数据,而 success 函数作为以下函数处理数据。

但是,您可以在成功函数中添加 status 和 xhr 变量。 status 变量包含以下字符串之一:“success”、“notmodified”、“error”、“timeout”或“parsererror”,xhr 变量包含返回的 XMLHttpRequest 对象
在w3schools上找到

$.getJSON(url, datatosend, function(data, status, xhr){
    if (status == "success"){
        //do something with the data
    }else if (status == "timeout"){
        alert("Something is wrong with the connection");
    }else if (status == "error" || status == "parsererror" ){
        alert("An error occured");
    }else{
        alert("datatosend did not change");
    }         
});

这样就很简单跟踪超时和错误,而无需实现请求完成后启动的自定义超时跟踪器。

希望这对仍在寻找该问题答案的人有所帮助。

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):

$(selector).getJSON(url,data,success(data,status,xhr))

most people implement that using

$.getJSON(url, datatosend, function(data){
    //do something with the data
});

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)

$.getJSON(url, datatosend, function(data, status, xhr){
    if (status == "success"){
        //do something with the data
    }else if (status == "timeout"){
        alert("Something is wrong with the connection");
    }else if (status == "error" || status == "parsererror" ){
        alert("An error occured");
    }else{
        alert("datatosend did not change");
    }         
});

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文