如何在没有jQuery的情况下用JavaScript打开JSON文件

How can I open a JSON file in JavaScript without jQuery?

本文关键字:JavaScript 打开 JSON 文件 情况下 jQuery      更新时间:2023-09-26

我正在用JavaScript编写一些代码。在这段代码中,我想读取一个json文件。此文件将从URL加载。

如何在JavaScript中的对象中获取此JSON文件的内容?

例如,这是我位于../json/main.json:的JSON文件

{"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{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); }
);

XHR可以用来打开文件,但你基本上会让它变得很难,因为jQuery让你更容易做到这一点。$.getJSON()让这变得很容易。我宁愿调用一行代码,也不愿尝试让整个代码块工作,但这取决于你。。。

我为什么不想使用jQuery是因为我的同事不想要它,因为他害怕脚本的速度。

如果他不能正确地评测本机VS jQuery,他甚至不应该编写本机代码

害怕意味着他不知道自己在做什么。如果你打算追求性能,你实际上需要知道如何使某些代码更快。如果你只是认为jQuery很慢,那么你走错了路。。。

JSON与jQuery没有任何关系。

您现在的代码没有任何问题。


为了存储变量mainStore,它是json中的一个变量。

您应该将json存储到一个变量中:

var myJSON = {"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]};
var mainStore = myJSON.mainStore;
//.. rest of your code.

我理解"读取json文件"意味着向返回json内容的url发出请求。如果是这样的话,你能解释一下为什么不想使用jQuery吗?它有$.ajax功能,非常适合这个功能,并涵盖了浏览器的差异。

如果你想读取文件,那么你必须在服务器端进行,例如php,并以某种方式将其提供给dom(有不同的方法),以便js可以使用它。使用js从磁盘读取文件是不可能的

function loadDoc() {
    const xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
       console.log(xhttp.responseText)
      }
    };
    xhttp.open("GET", "./user.json");
    xhttp.send();
  }

使用linux文件名结构命名您可以将responseText存储到一个变量或任何您想用它做的事情