【问题标题】:Ajax in javascript not workingjavascript中的Ajax不起作用
【发布时间】:2010-11-06 17:29:54
【问题描述】:
$(document).ready(function() {

$('#content').html('');
$.ajax({
        url:'data.json',
        dataType: "json",
        success: function(data) {
                $('#content').append('<p>'+data.rank+'</p>');
        }
});});

在这段代码中(有效)data.json 包含这种格式的 JSON 数据:

{
"user_id":"3190399",
"user_name":"Anand_Dasgupta",
"followers_current":"86",
"date_updated":"2009-06-04",
"url":"",
"avatar":"205659924\/DSC09920_normal.JPG",
"follow_days":"0","started_followers":"86",
"growth_since":0,
"average_growth":"0",
"tomorrow":"86",
"next_month":"86",
"followers_yesterday":"86",
"rank":176184,
"followers_2w_ago":null,
"growth_since_2w":86,
"average_growth_2w":"6",
"tomorrow_2w":"92",
"next_month_2w":"266",
"followersperdate":[]
}

此数据来自网址:

http://twittercounter.com/api/?username=Anand_Dasgupta&output=json&results=3
(点击网址获取数据)

但是当我将 $.ajax 函数中的 data.json 替换为包含相同数据的 URL 时,下面的代码似乎不起作用...

$(document).ready(function() {

$('#content').html('');
$.ajax({
      url:'http://twittercounter.com/api/username=Anand_Dasgupta&output=json&results=3',
        dataType: "json",
        success: function(data) {
                $('#content').append('<p>'+data.rank+'</p>');
        }
});});

我们将不胜感激任何有关此问题的帮助。
感谢期待,
阿南德

【问题讨论】:

    标签: ajax json url twitter


    【解决方案1】:

    问题是您正在尝试访问不同域上的 url(除非您实际上是在 twittercounter.com 上)。无论如何,如果您想执行浏览器出于安全考虑不允许的跨站点 AJAX 调用,您必须使用 JSONP“技巧”。您可以将 JSONP 与 jQuery 一起使用,看起来您正在使用它。最后我检查了一下,jQuery 需要一些服务器端配置,所以除非你可以改变你获得的数据,否则你必须手动执行 AJAX 请求,在这种情况下你可以使用 JSONP 方法获取它。

    【讨论】:

      【解决方案2】:

      基本上,您正在尝试访问跨域 AJAX 请求。这是不允许的,因为它往往会危及浏览器的安全性。您可以通过以下方式绕过它:

      http://code.google.com/p/cross-domain-ajax/

      诺亚

      编辑:6 月 29 日星期一 10:24:51 CDT 2009 googletorp FTW!

      【讨论】:

        猜你喜欢
        • 2013-06-28
        • 1970-01-01
        • 2011-07-07
        • 1970-01-01
        • 2017-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多