【问题标题】:jQuery doesn't return any API results in the Succes function of $.ajax() while using JSONPjQuery 在使用 JSONP 时不会在 $.ajax() 的 Succes 函数中返回任何 API 结果
【发布时间】:2011-05-29 08:49:57
【问题描述】:

我在从 jQuery $.ajax() 函数的 JSONP 数据类型中获取任何结果时遇到了很多麻烦。这是我的 jQuery 代码:

  $('#show_tweets').click(function(){
    $.ajax({
      type: 'get',
      url: 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=jquery',
      dataType: 'jsonp',
      succes: function(data) {
        $.each(data, function() {
          $('<div></div>')
            .hide()
            .append('<img src="'+ this.profile_image_url +'"/>')
            .append('<p>'+ this.text +'</p>')
            .appendTo('#tweets_gallery')
            .fadeIn();
        })
      },
      error: function() {
        alert('Iets gaat fout!!');
      }
    });
  });

我已将#show_tweets ID 分配给 P 标签。 #tweets_gallery 是一个空的 DIV。现在,我知道我也可以使用 $.getJSON() 函数,但我只想知道如何使用 $.ajax() 正确检索 JSONP 结果要求。我点击了几次,它没有输出任何东西。

提前致谢!

【问题讨论】:

标签: jquery ajax twitter jsonp


【解决方案1】:

如果由于您的错字而导致错误:

succes: function(data) 应该是success: function(data)

在回复您下面的评论时,profile_image_url 未定义的原因是因为根范围内没有属性。 twitter 返回的 JSON 格式为:

{
  "text" : "The twitter text",
  "user" : {
           "profile_image_url" : "http://path.to.profileimage/",
           ...
  },
  ...
}

所以this.text 存在(这就是您获得价值的原因),但您应该以this.user.profile_image_url 的身份访问个人资料图片

请参阅twitter API,了解 JSON 的结构。

【讨论】:

  • 大声笑,这正是问题所在!先生,您的眼光敏锐!好的,我还有最后一个问题:当我定义“this.profile_image_url”时,我的 AJAX 请求没有返回任何有用的信息。 “this.text”虽然完美。但是,“this.profile_image_url”实际上仍然是未定义的。我期待在这种情况下看到 jQuery 头像弹出。我的范围有错吗?
  • @Martijn1981 这是因为个人资料图像在您阅读的数据中的user 对象下。我已根据您的评论更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 2014-07-27
  • 2018-01-09
  • 2021-05-31
  • 1970-01-01
  • 2011-11-18
  • 2011-02-14
  • 2012-05-14
  • 2013-04-01
相关资源
最近更新 更多