简体   繁体   English

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

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

I am writing some code in JavaScript.我正在用 JavaScript 编写一些代码。 In this code i want to read a json file.在这段代码中,我想读取一个 json 文件。 This file will be loaded from an URL.该文件将从 URL 加载。

How can I get the contains of this JSON file in an object in JavaScript?如何在 JavaScript 的对象中获取此 JSON 文件的包含内容?

This is for example my JSON file located at ../json/main.json :例如,我的 JSON 文件位于../json/main.json

{"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]}

and i want to use it in my table.js file like this:我想在我的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>');
} 

Here's an example that doesn't require jQuery: 这是一个不需要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();
}

Call it as: 称之为:

loadJSON('my-file.json',
         function(data) { console.log(data); },
         function(xhr) { console.error(xhr); }
);

XHR can be used to open files, but then you're basically making it hard on yourself because jQuery makes this a lot easier for you. XHR可以用来打开文件,但是你基本上对自己很难,因为jQuery使你更容易。 $.getJSON() makes this so easy to do. $.getJSON()使这很容易做到。 I'd rather want to call a single line than trying to get a whole code block working, but that's up to you... 我宁愿打电话给单行而不是试图让整个代码块工作,但这取决于你......

Why i dont want to use jQuery is because the person i am working for doesn't want it because he is afraid of the speed of the script. 为什么我不想使用jQuery是因为我工作的人不想要它因为他害怕脚本的速度。

If he can't properly profile native VS jQuery, he shouldn't even be programming native code. 如果他无法正确配置本机VS jQuery,他甚至不应该编写本机代码。

Being afraid means he doesn't know what he is doing. 害怕意味着他不知道自己在做什么。 If you plan to go for performance, you actually need to know how to see how to make certain pieces of code faster. 如果您打算提高性能,实际上您需要知道如何更快地制作某些代码。 If you are only just thinking that jQuery is slow, then you are walking into the wrong roads... 如果你只是认为jQuery很慢,那么你走的是错误的道路......

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();
  }

Naming using the linux filename structure You can store the responseText to a variable or whatever you want to do with it使用 linux 文件名结构命名您可以将responseText存储到一个变量或任何您想用它做的事情

JSON has nothing to do with jQuery. JSON与jQuery 无关

There is nothing wrong with the code you have now. 你现在拥有的代码没有任何问题。


To store the variable mainStore , it is a variable in that json. 要存储变量mainStore ,它是json中的变量。

You should store that json to a variable: 你应该将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.

I understand that by "reading a json file" you mean making the request to the url that returns json content. 我理解通过“读取json文件”,你的意思是向返回json内容的url发出请求。 If so, then can you explain why you don't want to use jQuery for this purpose? 如果是这样,那么你能解释为什么你不想为此目的使用jQuery吗? It has $.ajax function that is perfectly suitable for this and covers the browsers' differences. 它具有$ .ajax功能,非常适合这种情况,并涵盖浏览器的差异。

If you want to read the file then you have to do it server-side, eg php and provide it somehow to the dom (there are different methods) so js can use it. 如果你想读取文件,那么你必须在服务器端进行,例如php并以某种方式提供给dom(有不同的方法),所以js可以使用它。 Reading file from disk with js is not possible. 无法使用js从磁盘读取文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM