【问题标题】:Read json file from localhost with javascript使用 javascript 从 localhost 读取 json 文件
【发布时间】:2013-03-20 03:21:53
【问题描述】:

我需要从本地主机读取.json 文件,但它不起作用!

文件内容如下:

[
 {"source":"tw1", 
  "text":"fubar"}, 

 {"source":"tw2", 
  "text":"foo"}
]

我使用以下命令设置了 localhost:python -m http.server 8888 &,这里发布了D3.js

我编写了以下 javascript 代码:

<script type="text/javascript" src="lib/jquery-1.9.1.js"></script>
   <script>
    $(document).ready(
        $.getJSON("http://localhost/test.json", function(data){
            document.write(data);

    });
    </script>  
 

【问题讨论】:

标签: javascript json localhost


【解决方案1】:

如果您在端口8888 上打开您的服务器,那么您必须在该端口上请求它:

$.getJSON("http://localhost:8888/test.json", function(data){

但要注意服务器必须设置correct CORS headers才能传递cross domain restrictions

第三个问题是您的代码无法编译:您缺少});。压痕不对称使它很明显:

$(document).ready(
    $.getJSON("http://localhost:8888/test.json", function(data){
        document.write(data);
    }); // <=== was missing
});

第四个问题是你不想在页面加载后使用document.write。您必须使用 DOM 操作方法编写,例如 $(document.body).append($('&lt;pre&gt;'+data+'&lt;/pre&gt;'));

【讨论】:

  • 感谢您的快速回复,}); 哪里不见了,这在&lt;/script&gt; 标签上方吗?
  • @dot 我编辑了。您应该尝试习惯于在代码中看到对称性。这就是我发现最明显错误的方式。
  • 如何在这个简单的服务器上设置正确的 CORS 标头,问这个愚蠢的问题!
【解决方案2】:

我认为问题在于您正在尝试访问计算机中的 json 文件,将 json 文件上传到在线服务器并访问该服务器,而不是您的计算机。

【讨论】:

    猜你喜欢
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 2021-11-29
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    相关资源
    最近更新 更多