无法在Google Chrome中获取JSON文件?

时间:2013-02-04 12:57:37

标签: javascript jquery json google-chrome

  

可能重复:
  Problems with jQuery getJSON using local files in Chrome

我的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文件都在同一个位置。如何解决?

2 个答案:

答案 0 :(得分:9)

Chrome根本不允许对本地文件进行ajax调用。请参阅 This

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

答案 1 :(得分:3)

检查答案 here

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