【发布时间】:2014-11-12 21:39:19
【问题描述】:
我已经查看了 SO 中的几个问题,并且在几个方向上被引导并没有结果。
这是我的 JQuery/HTML:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
alert ("hi");
$.getJSON("/Users/rabdelaz/Desktop/ACTFast/PM-MD.json",function(result){ //This is Version 1
//$.getJSON("http://172.28.101.197:3000/tests.json",function(result){ //This is Version 2
alert ("file is good");
});
});</script>
</body>
</html>
首先,我在打开文件之前尝试open -a "Google Chrome" --args --allow-file-access-from-files(我在 OS x 上)。我在上面的代码中使用了Version 1。这给了我这个:
XMLHttpRequest cannot load file:///Users/rabdelaz/Desktop/ACTFast/PM-MD.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
这让我觉得我应该尝试将文件托管在我正在运行的 Rails 服务器上。
所以我尝试从位于另一台机器上的 rails 服务器提供静态 JSON。为此,我在上面使用了Version 2。这给了我这个:
XMLHttpRequest cannot load http://172.28.101.197:3000/tests.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
为了完整起见,这里是为我的 JSON 提供服务的控制器:
@@data = File.read("/home/rabdelaz/PM-MD.json")
# GET /tests
# GET /tests.json
def index
render :text => @@data.to_s, :callback => params['callback']
end
我很高兴在这里放弃 Rails 服务器,但我认为这会有所帮助。我可以使用一些帮助来决定前进的方向。
【问题讨论】:
-
getJSON 请求具有相同的源策略
-
如何绕过此政策?我应该使用不同的方法/功能吗?
-
我现在很痛苦地意识到这项政策......
-
在文档中说您可以使用 .jsonp。还有stackoverflow.com/questions/3506208/jquery-ajax-cross-domain
标签: jquery ruby-on-rails json