4

我需要.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>  
 
4

2 回答 2

4

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

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

但请注意,如果您希望能够通过跨域限制,服务器必须设置正确的 CORS 标头

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

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

A fourth problem is that you wan't use document.write once the page is loaded. You must write using DOM manipulation methods, like $(document.body).append($('<pre>'+data+'</pre>'));

于 2013-03-29T12:17:04.550 回答
1

I think the problem is that you're trying to access the json file in your computer, upload your json file to a online server and access that instead of the one that is one your computer.

于 2017-02-26T07:44:06.057 回答