本文介紹了如何在沒有 jQuery 的情況下在 JavaScript 中打開 JSON 文件?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在用 JavaScript 編寫一些代碼.在這段代碼中,我想讀取一個 json 文件.該文件將從 URL 加載.
I am writing some code in JavaScript. In this code i want to read a json file. This file will be loaded from an URL.
如何在 JavaScript 的對象中獲取此 JSON 文件的包含內容?
How can I get the contains of this JSON file in an object in JavaScript?
例如我的 JSON 文件位于 ../json/main.json
:
This is for example my JSON file located at ../json/main.json
:
{"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]}
我想在我的 table.js
文件中使用它,如下所示:
and i want to use it in my table.js
file like this:
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 的例子:
Here's an example that doesn't require 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); }
);
這篇關于如何在沒有 jQuery 的情況下在 JavaScript 中打開 JSON 文件?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!