Error handling in getJSON calls

后端 未结 9 1633
野的像风
野的像风 2020-11-28 02:09

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?

相关标签:
9条回答
  • 2020-11-28 02:26

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

    0 讨论(0)
  • 2020-11-28 02:40

    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);
        });
    
    0 讨论(0)
  • 2020-11-28 02:41

    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);
    }
    
    0 讨论(0)
提交回复
热议问题