【问题标题】:Loading static JSON from local FS or remote rails server从本地 FS 或远程 Rails 服务器加载静态 JSON
【发布时间】: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 服务器,但我认为这会有所帮助。我可以使用一些帮助来决定前进的方向。

【问题讨论】:

标签: jquery ruby-on-rails json


【解决方案1】:

您可以尝试将其添加到您的 rails 方法中

 headers['Access-Control-Allow-Origin'] = '*'
 headers['Access-Control-Request-Method'] = '*'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多