将本地JSON文件读入变量 [英] read local JSON file into variable
问题描述
例如,我已经在本地系统中保存了一个JSON文件并创建了一个Javascript文件,以便读取JSON文件并打印出数据.这是JSON文件:
I have saved a JSON file in my local system and created a Javascript file in order to read the JSON file and print data out, for instance. Here is the JSON file:
[
{"Titel":"a",
"Timestamp":"2017-05-18 22:11",
"Text":"a",
"img":"a.jpg",
"FullText":"a"
},
{"Titel":"b",
"Timestamp":"2017-08-08 22:11",
"Text":"b",
"img":"b.jpg",
"FullText":"b" }]
可以说这是将您带到JSON文件的路径:
Lets say this is the path where it takes you to the JSON file:
../news_data.json
任何人都可以帮助我编写一段简单的代码来读取JSON文件并使用Javascript打印其中的数据.我是Java的新手,需要一些简单的开始.非常感谢您的协助.
Could anyone please help me with writing a simple piece of codes to read the JSON file and print the data inside it in Javascript. I am very new to Javascript and need something simple to start with. Your assistance would be very much appreciated.
推荐答案
这是不使用jQuery的一种方法.
Here's a way to do it without jQuery.
首先创建此功能:
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', '../news_data.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(JSON.parse(xobj.responseText));
}
};
xobj.send(null);
}
然后您可以通过简单地调用如下代码来使用它:
Then you can use it by simply calling something like this:
loadJSON(function(json) {
console.log(json); // this will log out the json object
});
我通过简单地谷歌搜索读取本地json文件javascript"(源)
I found this by simply googling "read local json file javascript" (source)
这篇关于将本地JSON文件读入变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!