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 呼び出しを行うことは許可されていません。これを参照

ただし、ローカルで動作させたい場合は、フラグ --allow-file-access-from-files を使用して Chrome を起動できます。

于 2013-02-04T13:08:48.453 に答える
3

ここで答えを確認してください

http経由でjsonファイルにアクセスするか、jsonpを使用してみてください

于 2013-02-04T13:07:38.787 に答える