I am using the following code to get the j开发者_如何学Goson feed of a twitter users friends using the 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,i.e. when no such twitter user exists the callback function i defined is not executed, and the ajax loading animation does not get hidden.
So, is there a way i can determine in code whether the request for the json feed is failing,and then hide the loading animation ?
Thank You.
the ccallback can return 2 arguments one of which is a textStatus that you can test against.
$.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
}
via: http://docs.jquery.com/Ajax/jQuery.getJSON
You are not catching the error condition. From the example below you can use an if statement or a switch to handle both situations.
http://docs.jquery.com/Ajax/jQuery.getJSON says:
callback (Optional) Function
A function to be executed whenever the data is loaded successfully.
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 Working Example thanks go to jQuery ajax (jsonp) ignores a timeout and doesn't fire the error event.
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();
}
});
精彩评论