jQuery getJSON 调用中的错误处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1740218/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:04:26  来源:igfitidea点击:

Error handling in getJSON calls

jquerycross-domainjsonpgetjson

提问by Ajay

How can you handle errors in a getJSON call? Im trying to reference a cross-domain script service using jsonp, how do you register an error method?

如何处理 getJSON 调用中的错误?我正在尝试使用jsonp引用跨域脚本服务,您如何注册错误方法?

回答by Luciano Costa

$.getJSON()is a kind of abstraction of a regular AJAX call where you would have to tell that you want a JSON encoded response.

$.getJSON()是对常规 AJAX 调用的一种抽象,您必须在其中告知您需要 JSON 编码的响应。

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

You can handle errors in two ways: generically (by configuring your AJAX calls before actually calling them) or specifically (with method chain).

您可以通过两种方式处理错误:一般(通过在实际调用之前配置 AJAX 调用)或专门(使用方法链)。

'generic' would be something like:

“通用”将类似于:

$.ajaxSetup({
      "error":function() { alert("error");  }
});

And the 'specific' way:

和“特定”的方式:

$.getJSON("example.json", function() {
  alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });

回答by frenetix

Someone give Luciano these points :) I just tested his answer -had a similar question- and worked perfectly...

有人给卢西亚诺这些要点:) 我刚刚测试了他的答案 - 有一个类似的问题 - 并且完美地工作......

I even add my 50 cents:

我什至加上我的 50 美分:

.error(function(jqXHR, textStatus, errorThrown) {
        console.log("error " + textStatus);
        console.log("incoming Text " + jqXHR.responseText);
    })

回答by user2314737

Here's my addition.

这是我的补充。

From http://www.learnjavascript.co.uk/jq/reference/ajax/getjson.htmland the official source

来自http://www.learnjavascript.co.uk/jq/reference/ajax/getjson.html官方来源

"The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead."

" jQuery 1.5 中引入的 jqXHR.success()、jqXHR.error() 和 jqXHR.complete() 回调方法自 jQuery 1.8 起已弃用。要为最终删除它们准备代码,请使用 jqXHR.done()、jqXHR .fail() 和 jqXHR.always() 代替。

I did that and here is Luciano's updated code snippet:

我这样做了,这里是 Luciano 的更新代码片段:

$.getJSON("example.json", function() {
  alert("success");
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function() { alert('getJSON request failed! '); })
.always(function() { alert('getJSON request ended!'); });

And with error description plus showing all json data as a string:

并带有错误描述以及将所有 json 数据显示为字符串:

$.getJSON("example.json", function(data) {
  alert(JSON.stringify(data));
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); })
.always(function() { alert('getJSON request ended!'); });

If you don't like alerts, substitute them with console.log

如果您不喜欢警报,请将其替换为 console.log

$.getJSON("example.json", function(data) {
  console.log(JSON.stringify(data));
})
.done(function() { console.log('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { console.log('getJSON request failed! ' + textStatus); })
.always(function() { console.log('getJSON request ended!'); });

回答by Tom Groentjes

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

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

The getJSON structure is as follows (found on http://api.jqueri.com):

getJSON 结构如下(可在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.

他们使用 url var 提供指向 JSON 数据的链接,将 datatosend 作为添加"?callback=?"必须发送的变量和其他变量以获取返回的正确 JSON 数据的位置,以及作为处理数据的函数的成功函数.

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)

但是,您可以在成功函数中添加 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");
    }         
});

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.

希望这可以帮助仍在寻找此问题答案的人。

回答by Pavlo O.

$.getJSON("example.json", function() {
  alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })

It is fixed in jQuery 2.x; In jQuery 1.x you will never get an error callback

它在 jQuery 2.x 中得到修复;在 jQuery 1.x 中你永远不会得到错误回调

回答by phil294

Why not

为什么不

getJSON('get.php',{cmd:"1", typeID:$('#typesSelect')},function(data) {
    // ...
});

function getJSON(url,params,callback) {
    return $.getJSON(url,params,callback)
        .fail(function(jqXMLHttpRequest,textStatus,errorThrown) {
            console.dir(jqXMLHttpRequest);
            alert('Ajax data request failed: "'+textStatus+':'+errorThrown+'" - see javascript console for details.');
        })
}

??

??

For details on the used .fail()method (jQuery 1.5+), see http://api.jquery.com/jQuery.ajax/#jqXHR

有关所用.fail()方法(jQuery 1.5+)的详细信息,请参阅http://api.jquery.com/jQuery.ajax/#jqXHR

Since the jqXHRis returned by the function, a chaining like

由于jqXHR是由函数返回的,因此链式类似于

$.when(getJSON(...)).then(function() { ... });

is possible.

是可能的。

回答by Nick Woodhams

I was faced with this same issue, but rather than creating callbacks for a failed request, I simply returned an error with the json data object.

我遇到了同样的问题,但我没有为失败的请求创建回调,而是简单地返回一个带有 json 数据对象的错误。

If possible, this seems like the easiest solution. Here's a sample of the Python code I used. (Using Flask, Flask's jsonify f and SQLAlchemy)

如果可能,这似乎是最简单的解决方案。这是我使用的 Python 代码示例。(使用 Flask,Flask 的 jsonify f 和 SQLAlchemy)

try:
    snip = Snip.query.filter_by(user_id=current_user.get_id(), id=snip_id).first()
    db.session.delete(snip)
    db.session.commit()
    return jsonify(success=True)
except Exception, e:
    logging.debug(e)
    return jsonify(error="Sorry, we couldn't delete that clip.")

Then you can check on Javascript like this;

然后你可以像这样检查Javascript;

$.getJSON('/ajax/deleteSnip/' + data_id,
    function(data){
    console.log(data);
    if (data.success === true) {
       console.log("successfully deleted snip");
       $('.snippet[data-id="' + data_id + '"]').slideUp();
    }
    else {
       //only shows if the data object was returned
    }
});

回答by Alex Alonso

In some cases, you may run into a problem of synchronization with this method. I wrote the callback call inside a setTimeoutfunction, and it worked synchronously just fine =)

在某些情况下,您可能会遇到使用此方法进行同步的问题。我在一个setTimeout函数中编写了回调调用,它同步工作就好了 =)

E.G:

例如:

function obterJson(callback) {


    jqxhr = $.getJSON(window.location.href + "js/data.json", function(data) {

    setTimeout(function(){
        callback(data);
    },0);
}