JQuery getJSON函数

时间:2009-10-22 20:55:38

标签: jquery ajax json twitter

我使用以下代码使用twitter api获取Twitter用户朋友的json feed:

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

这在twitter句柄有效时有效。但如果它无效,即。当没有这样的twitter用户存在时,我没有执行我定义的回调函数,并且没有隐藏ajax加载动画。

那么,有没有办法可以在代码中确定json feed的请求是否失败,然后隐藏加载动画?

谢谢。

2 个答案:

答案 0 :(得分:1)

ccallback可以返回2个参数,其中一个是你可以测试的textStatus。

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

答案 1 :(得分:1)

您没有发现错误情况。从下面的示例中,您可以使用if语句或开关来处理这两种情况。

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

回调(可选)功能
成功加载数据时要执行的函数。

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
}

修改 工作示例谢谢转到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();
            }
});