Error handling in getJSON calls

后端 未结 9 1658
野的像风
野的像风 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: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);
        });
    

提交回复
热议问题