getJSON 调用中的错误处理

发布于 2024-08-11 03:23:06 字数 57 浏览 1 评论 0原文

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(9

倾城泪 2024-08-18 03:23:06

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

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

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

“通用”类似于:

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

“特定”方式:

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

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

$.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).

'generic' would be something like:

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

And the 'specific' way:

$.getJSON("example.json", function() {
  alert("success");
})
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });
吻泪 2024-08-18 03:23:06

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

我什至加上了我的 50 美分:

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

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

I even add my 50 cents:

.error(function(jqXHR, textStatus, errorThrown) {
        console.log("error " + textStatus);
        console.log("incoming Text " + jqXHR.responseText);
    })
但可醉心 2024-08-18 03:23:06

这是我的补充。

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

jqXHR.success()、jqXHR.error()、和 jqXHR.complete() 回调
从 jQuery 1.8 开始,jQuery 1.5 中引入的方法已被弃用。到
为最终删除准备代码,使用 jqXHR.done(),
jqXHR.fail() 和 jqXHR.always() 。
"

我这样做了,这是 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!'); });

并带有错误描述,并将所有 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!'); });

如果您不喜欢警报,用 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!'); });

Here's my addition.

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

"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.
"

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

$.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:

$.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

$.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!'); });
怀里藏娇 2024-08-18 03:23:06

我知道自从有人在这里回答以来已经有一段时间了,发帖者可能已经从这里或其他地方得到了他的答案。不过,我确实认为这篇文章将帮助任何人在执行 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 作为添加 < 的位置code>"?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 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.

触ぅ动初心 2024-08-18 03:23:06
$.getJSON("example.json", function() {
  alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })

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

$.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

时光病人 2024-08-18 03:23:06

为什么不呢

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.');
        })
}

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

链接。

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

由于 jqXHR 由函数返回,因此可以进行

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

Since the jqXHR is returned by the function, a chaining like

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

is possible.

┊风居住的梦幻卍 2024-08-18 03:23:06

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

如果可能的话,这似乎是最简单的解决方案。这是我使用的 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.")

然后你可以像这样检查 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
    }
});

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.

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)

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;

$.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
    }
});
〃安静 2024-08-18 03:23:06

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

EG:

function obterJson(callback) {


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

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

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

E.G:

function obterJson(callback) {


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

    setTimeout(function(){
        callback(data);
    },0);
}
2024-08-18 03:23:06

这是一个相当古老的线程,但它确实出现在 Google 搜索中,所以我想我会使用 Promise 添加 jQuery 3 答案。此代码片段还显示:

  • 您不再需要切换到 $.ajax 来传递不记名令牌
  • 使用 .then() 确保您可以同步处理任何结果(我遇到了这个问题 .always() 回调触发太快 - 虽然我不确定这是100%正确)
  • 我使用 .always() 简单地显示结果,无论是积极的还是消极的
  • 在 .always() 函数中,我使用 HTTP 状态代码和消息正文更新两个目标

代码片段是:

    $.getJSON({
         url: "https://myurl.com/api",
         headers: { "Authorization": "Bearer " + user.access_token}
    }).then().always(   function (data, textStatus) {
        $("#txtAPIStatus").html(data.status);
        $("#txtAPIValue").html(data.responseText);
    });

This is quite an old thread, but it does come up in Google search, so I thought I would add a jQuery 3 answer using promises. This snippet also shows:

  • You no longer need to switch to $.ajax to pass in your bearer token
  • Uses .then() to make sure you can process synchronously any outcome (I was coming across this problem .always() callback firing too soon - although I'm not sure that was 100% true)
  • I'm using .always() to simply show the outcome whether positive or negative
  • In the .always() function I'm updating two targets with the HTTP Status code and message body

The code snippet is:

    $.getJSON({
         url: "https://myurl.com/api",
         headers: { "Authorization": "Bearer " + user.access_token}
    }).then().always(   function (data, textStatus) {
        $("#txtAPIStatus").html(data.status);
        $("#txtAPIValue").html(data.responseText);
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文