问题 无法在Google Chrome中获取JSON文件? [重复]


可能重复:
使用Chrome中的本地文件的jQuery getJSON问题 

我的html文件“index.html”和“contact.json”都在同一个文件夹中

我的代码来获取json文件

function loadData(fileName) { 
    // getting json from a remote file
    // by returning the jqXHR object we can use the .done() function on it
    // so the callback gets executed as soon as the request returns successfully
    return $.getJSON( fileName + ".json");
}

function fillDataTable(data) {
//  alert(data);
    // iterate over each entry in the data.info array
    $.each(data.info, function(index, element) {
    // append it to the table
    $("#contact").append('<tr><td>' + element.name + '</td><td>'+ element.email +'</td><td>' + element.phone +'</td><td>' + '<input type="button" id="edit" onclick="edit(this.name)" name="'+ element.name +'" value="Edit"></input>' +'</td></tr>')
    }); 
}

$(document).ready(function(){

    // the file's name. "contact" in this example.
    var myFile = "contact";

    loadData(myFile).done(function(data) {
        // check if we acutally get something back and if the data has the info property
        if (data && data.info) {
            // now fill the data table with our data
            fillDataTable(data)
        }
    });
});

我的json文件

{
    "info": [
        {
            "name":"Noob Here",
            "email":"myemail@server.com",
            "phone":"123456"
        },
        {
            "name":"Newbie There",
            "email":"hisemail@server.com",
            "phone":"589433"
        }
    ]
}

我的HTML

<div id="container-1">
    <ul>
        <li><a href="#fragment-1">List</a></li>
    </ul>   
    <div id="fragment-1">
        <table id="contact">
        <tr>
        <th> Name </th>
        <th>E-mail </th>
        <th> Phone </th>
        </tr>
        </table>
    </div>
</div>

CDN给

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>

代码工作正常 Firefox 但没有工作 Google Chrome

获得的错误 Google Chrome

XMLHttpRequest cannot load file:///home/user/jquery/contact.json. Origin null is not allowed by Access-Control-Allow-Origin.

html和json文件都在同一个位置。怎么解决?


6402
2018-02-04 12:57


起源

Chrome有相当不错的开发者工具(热门 F12 打开它们)。您至少应该能够看到可能的错误消息并找出执行哪些代码以及哪些代码不执行。 - Álvaro González
更新了错误代码的问题 - Okky
@ h2ooooooo:在我发布这个问题之前,我没有发现getJson或Chrome有问题。所以我认为它不重复。 - Okky


答案:


Chrome根本不允许对本地文件进行ajax调用。参考 这个

但是,如果您希望Chrome在本地运行,则可以使用标记--allow-file-access-from-files启动Chrome。


9
2018-02-04 13:08



是马塞尔,这似乎是首选的标志,因为它被认为更安全。现在编辑我的答案。谢谢。 - Peter Herdenborg


检查答案 这里

尝试通过http访问json文件或使用jsonp


3
2018-02-04 13:07



然后OP必须安装本地Web服务器。 - Marcel Korpel