从localhost或file://访问JSON服务

问题描述

您遇到了同源策略限制- 您的脚本无法访问除加载域以外的任何其他域。

  1. 您可以尝试JSONP-这是跨域获取数据的一种常见解决方案:

您的代码看起来像这样(注意callback=?URL的添加):

    $.getJSON("http://search.twitter.com/search.json?q=somequery&result_type=recent&count=9&callback=?", 
          {},
          function (data) {
                  $.each(data.items, doSomething2);  
     });
  1. 一个选择是设置代理-您可以将Apache httpd用作代理/反向代理来解决此限制。

解决方法

我正在制作一个打算在PC上本地运行的html页面,最好不要在本地服务器上运行(file://)。我还使用jQuery使操作/ AJAX更加容易。

我正在尝试从twitter API加载2个结果,但出现错误。代码如下:

$.getJSON("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=someuser&count=9",{},function (data) {
        $.each(data.items,doSomething1);
    });
$.getJSON("http://search.twitter.com/search.json?q=somequery&result_type=recent&count=9",doSomething2);
    });

我也尝试了以下代码,但没有改变结果。

$.getJSON("http://api.twitter.com/1/statuses/user_timeline.json",{
        count:          "9",screen_name:    "someuser"
    },function(data) {
        $.each(data.items,updateAWTweets);
    });
$.getJSON("http://search.twitter.com/search.json",{
        q:              "somequery",result_type:    "recent",count:          "9"
    },updateHashTagTweets);
    });

我在chrome中(在本地服务器上)收到以下错误:

XMLHttpRequest cannot load http://search.twitter.com/search.json?q=somequery&result_type=recent&count=9. Origin http://localhost:62153 is not allowed by Access-Control-Allow-Origin.

或(带有file://链接)

XMLHttpRequest cannot load http://api.twitter.com/1/statuses/user_timeline.json?screen_name=someuser&count=9. Origin null is not allowed by Access-Control-Allow-Origin.

有谁知道我该如何解决?