从localhost或file://访问JSON服务 [英] Accessing JSON service from localhost or file://
问题描述
我正在制作一个打算在PC上本地运行的html页面,最好不要运行本地服务器(file://)。我也使用jQuery使操作/ AJAX更容易。
I am making a html page intended to be run locally on a PC, preferably without a local server runing (file://). I am also using jQuery to make manipulation/AJAX a little easier.
我试图从twitter API加载2个结果,但是我收到错误。代码如下:
I am trying to load 2 results from the twitter API, but I get an error. The code is as follows:
$.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", {},
function (data) {
$.each(data.items, doSomething2);
});
我也试过以下代码,但没有改变结果。
I also tried the following code, but it didn't change the outcome.
$.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"
},
function(data) {
$.each(data.items, updateHashTagTweets);
});
我在chrome中遇到以下错误(在本地主机服务器上):
I get the following error in chrome (on a localhost server):
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.
或(带文件://链接)
or (with a file:// link)
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.
有谁知道如何解决这个问题?
Does anyone know how I can fix this?
推荐答案
您正在遇到同样的情况 - 原始政策限制 - 您的脚本无法访问除加载它之外的任何其他域。
You're running into the same-origin policy restriction - your script can't access any other domain apart from the one it was loaded from.
-
您可以尝试 JSONP - 这是获取数据的常用解决方案跨域:
You could give JSONP a try - that's one common solution to getting data across domains:
- http://www.chazzuka.com/blog/?p=221
- http://jquery-howto.blogspot.com/2009/04/twitter-jsonjsonp-api-url.html
- http://www.chazzuka.com/blog/?p=221
- http://jquery-howto.blogspot.com/2009/04/twitter-jsonjsonp-api-url.html
您的代码看起来像这样(注意添加 callba ck =?
到URL):
Your code would look something like this (note the addition of callback=?
to the URL):
$.getJSON("http://search.twitter.com/search.json?q=somequery&result_type=recent&count=9&callback=?",
{},
function (data) {
$.each(data.items, doSomething2);
});
另一种选择是设置代理 - 您可以使用Apache httpd作为代理/反向代理来解决这个限制。
Another option is to setup a proxy - you can use Apache httpd as a proxy/reverse proxy to get around this restriction.
这篇关于从localhost或file://访问JSON服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!