如何加载,并将本地JSON保存到变量中

时间:2014-01-01 05:19:02

标签: javascript jquery json

我对此非常陌生,尝试通过测验来关注http://javascriptissexy.com/how-to-learn-javascript-properly/,欢迎任何其他建议。我把JSON文件放在js的底部作为注释。

http://jsfiddle.net/Atlas_/Mgyc5/

原本是圣杯? :我

var theQuiz;
$.getJSON("package.json", function (json) {
    theQuiz = json;
});

3 个答案:

答案 0 :(得分:2)

尝试这样的事情

JSON FILE [json.js]

 var country = {name:"india",code:"IND"};

HTML文件

// adding file in script
<script src="json.js"></script>

//using json in script
<script>
  country.name // will give india
</script>

答案 1 :(得分:2)

谢谢大家,我通过检查和重新检查开发控制台来解决这个问题,但主要是难以置信地盯着显示器。我现在实际上需要帮助才能让它与服务器一起工作,包括一个本地服务器,但没有运气。

有价值的课程

$.getJSON("package.json", /*loads, if in the same folder*/ function (json) {
theQuiz = json.quiz; // Had to make sure to pick out the array because JSON put it into an extra object
console.log(theQuiz); // object Array
console.log(json);  // object Object
console.log(theQuiz[0].question); // Works! "How many times your heart beats in a day?(choose the closest)"
// but it's not working because js doesn't wait for JSON to load and it starts using the variables that doesn't exist yet
});

解决方案

$.ajax({
dataType: "json",
async: false, // Makes sure to wait for load
url: "package.json", //  https://www.dropbox.com/s/fmw63i4v7dtnx6t/package.json
'success': function (json) {
    theQuiz = json.quiz;
    console.log(json);  // object Object
    console.log(theQuiz); // object Array
    // Finishes loading before js starts using it, and works as intended
}
});

答案 2 :(得分:-1)

使用getJSON,您可以使用GET HTTP请求从服务器加载JSON编码的数据。您无法使用该功能加载本地文件。您可以加载本地文件,但这不是很容易。请查看以下链接。

Local file access with javascript

另请检查

Trying to load local JSON file to show data in a html page using JQuery