【问题标题】:JQuery getJSON functionjQuery getJSON 函数
【发布时间】:2010-12-09 06:07:57
【问题描述】:

我正在使用以下代码获取使用 twitter api 的 twitter 用户朋友的 json 提要:

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用户时,我定义的回调函数不会被执行,并且ajax加载动画不会被隐藏。

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

谢谢。

【问题讨论】:

    标签: jquery ajax json twitter


    【解决方案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
    }
    

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

    【讨论】:

    • 据我所知,这实际上不起作用:成功时, textStatus 为空;失败时,该函数甚至不会被调用
    【解决方案2】:

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

    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();
                }
    });
    

    【讨论】:

    • 感谢 Tony 的回复,但我不清楚将 textStatus 参数添加到回调函数有什么帮助,因为如果数据未成功加载,该函数将不会被执行。那么如何检查 textStatus 变量的值呢?能否请您展示一些 sn-p 来演示...谢谢。
    • 显然jquery处理jsonp的方式有问题。感谢这里的 José Basilio:stackoverflow.com/questions/1002367/… 我将用一个工作示例编辑我的帖子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多