JQuery getJSON function

I use the following code to get the json channel of friends of Twitter users using twitter api:

var url = "http://twitter.com/statuses/friends/"+twitter_handle+".json?callback=?";

//show ajax loading animation
$('#loading').show();

$.getJSON(url, function(data) {
   //hide ajax loading animation 
   $('#loading').hide();
   //Processing the JSON here
   //...
}); 

This works when the twitter handle is valid. But if it is invalid, that is. when such a Twitter user does not exist, the i callback function defined is not executed, and the ajax loading animation is not hidden.

So, is there a way that I can determine in the code if the request for the json feed is being executed and then hide the loading animation?

Thanks.

+3
source share
2 answers

ccallback can return 2 arguments, one of which is textStatus, with which you can test.

$.getJSON(url, function (data, textStatus) {
  // data will be a jsonObj
  // textStatus will be one of the following values: 
  //   "timeout","error","notmodified","success","parsererror"
  this; // the options for this ajax request
}

: http://docs.jquery.com/Ajax/jQuery.getJSON

+1

. if .

http://docs.jquery.com/Ajax/jQuery.getJSON :

callback ()
, , .

function (data, textStatus) {
  // data will be a jsonObj
  // textStatus will be one of the following values: 
  //   "timeout","error","notmodified","success","parsererror"
  this; // the options for this ajax request
}

Edit : jQuery ajax (jsonp) - .

        var twitter_handle = 'FakePersonx';
        var url = "http://twitter.com/statuses/friends/"+twitter_handle+".json?callback=?";

        $.jsonp({
            type: "GET",
            url: url,
            data: {},
            async:true,
            contentType: "application/json; charset=utf-8",
            dataType: "jsonp",
            success: function(data) {
                alert(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert('error');
            },
            beforeSend: function (XMLHttpRequest) {
                alert('Before Send');
                $('#loading').show();
            },
            complete: function (XMLHttpRequest, textStatus) {
                alert('Complete');
                $('#loading').hide();
            }
});
+1

Source: https://habr.com/ru/post/1720833/


All Articles