使用 javascript 从本地主机读取 json 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15703001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:47:13  来源:igfitidea点击:

Read json file from localhost with javascript

javascriptjsonlocalhost

提问by dot

I'm very new to javascript so I need a little help! I need to read a ".json" file from my localhost, but it didn't work!

我对 javascript 很陌生,所以我需要一些帮助!我需要从我的本地主机读取“.json”文件,但它没有用!

The contents of the file are as follows:

文件内容如下:

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

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

I set up the localhost with the command: python -m http.server 8888 &, which is posted D3.jshere.

我设置了该命令的本地主机:蟒蛇-m http.server 8888和,这是公布D3.js这里。

I wrote the following javascript code:

我写了以下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>  

采纳答案by Denys Séguret

If you open your server on port 8888, then you must request it on that port :

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

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

But beware that the server must set the correct CORS headersif you want to be able to pass cross domain restrictions.

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

A third problem is that your code can't compile : you're missing a });. The indentation asymmetry makes it obvious :

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

$(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.writeonce the page is loaded. You must write using DOM manipulation methods, like $(document.body).append($('<pre>'+data+'</pre>'));

第四个问题是document.write页面加载后您将无法使用。您必须使用 DOM 操作方法进行编写,例如$(document.body).append($('<pre>'+data+'</pre>'));

回答by Erick Mg

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.

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