11

可能重复:
在 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 文件都在同一个位置。如何解决?

4

2 回答 2

9

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

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

于 2013-02-04T13:08:48.453 回答
3

在这里检查答案

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

于 2013-02-04T13:07:38.787 回答