我在JavaScript中编写一些代码。在这段代码中,我想读一个json文件。该文件将从URL加载。
如何在JavaScript中的对象中获取JSON文件的内容?
这是例如我的JSON文件位于../json/main.json:
- {"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',{vehicle:'3',description:'nothing to say'}]}
我想在我的table.js文件中使用它:
- for (var i in mainStore)
- {
- document.write('<tr class="columnHeaders">');
- document.write('<td >'+ mainStore[i]['vehicle'] + '</td>');
- document.write('<td >'+ mainStore[i]['description'] + '</td>');
- document.write('</tr>');
- }
解决方法
这里有一个不需要jQuery的例子:
- function loadJSON(path,success,error)
- {
- var xhr = new XMLHttpRequest();
- xhr.onreadystatechange = function()
- {
- if (xhr.readyState === XMLHttpRequest.DONE) {
- if (xhr.status === 200) {
- if (success)
- success(JSON.parse(xhr.responseText));
- } else {
- if (error)
- error(xhr);
- }
- }
- };
- xhr.open("GET",path,true);
- xhr.send();
- }
称为:
- loadJSON('my-file.json',function(data) { console.log(data); },function(xhr) { console.error(xhr); }
- );