【问题标题】:Cross domain ajax response failing跨域ajax响应失败
【发布时间】:2010-11-07 14:28:55
【问题描述】:

好吧...所以我已经和这条鳕鱼扭来扭去有一段时间了...

首先我使用了这个有效的代码......


$(document).ready(function() {
$('#content').html('');
$.ajax({
        url:'data.json',
        dataType: "json",
        success: function(data) {
                $('#content').append('

'+data.rank+'

'); } });});

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

{ "user_id":"3190399", "user_name":"Anand_Dasgupta", "followers_current":"86", "date_updated":"2009-06-04", “网址”:“”, "头像":"205659924/DSC09920_normal.JPG", "follow_days":"0","started_followers":"86", "growth_since":0, “平均增长”:“0”, “明天”:“86”, "下个月":"86", "followers_yesterday":"86", “排名”:176184, "followers_2w_ago":null, “growth_since_2w”:86, "average_growth_2w":"6", “明天_2w”:“92”, "next_month_2w":"266", “追随者”:[] }

此数据来自网址:

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

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


$(document).ready(function() {
$('#content').html('');
$.ajax({
      url:'@987654322@',
        dataType: "json",
        success: function(data) {
                $('#content').append('

'+data.rank+'

'); } });});

我之前在 StackOverflow 上提出过这个问题,回答是这是一个跨域问题。

所以我阅读了有关跨域 ajax 请求的信息,这是我想出的代码:


$(document).ready(function() {                      
    $('form#search').bind("submit", function(e){                            
            e.preventDefault();
            $('#content').html('');

// Define the callback function
  function get(jsonData) {     
     $('#content').append('

'+jsonData.rank+'

'); bObj.removeScriptTag(); } // The web service call var req = 'http://twittercounter.com/api/?username=Anand_Dasgupta&output=json&results=3&callback=get'; // Create a new request object bObj = new JSONscriptRequest(req); // Build the dynamic script tag bObj.buildScriptTag(); // Add the script tag to the page bObj.addScriptTag(); }); });

但似乎没有工作。

如果有人可以提供任何帮助,我们将不胜感激。 我已经给出了整个代码,以便任何人都可以自己测试。

谢谢 阿南德

【问题讨论】:

    标签: ajax json twitter cross-domain


    【解决方案1】:

    你必须看看有问题的网站是否支持JSONP

    您还必须在设置为 'jsonp' 的 ajax 调用中使用 dataType 选项,并指定正确的回调参数。

    【讨论】:

      猜你喜欢
      • 2010-11-07
      • 2015-01-28
      • 2016-01-10
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      • 2011-11-17
      • 1970-01-01
      相关资源
      最近更新 更多