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

前端 未结 4 503
清歌不尽
清歌不尽 2020-11-27 15:20

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.

How can I get the contains of this JSON file in

相关标签:
4条回答
  • 2020-11-27 15:31

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

    Call it as:

    loadJSON('my-file.json',
             function(data) { console.log(data); },
             function(xhr) { console.error(xhr); }
    );
    
    0 讨论(0)
  • 2020-11-27 15:33

    I understand that by "reading a json file" you mean making the request to the url that returns json content. If so, then can you explain why you don't want to use jQuery for this purpose? It has $.ajax function that is perfectly suitable for this and covers the browsers' differences.

    If you want to read the file then you have to do it server-side, e.g. php and provide it somehow to the dom (there are different methods) so js can use it. Reading file from disk with js is not possible.

    0 讨论(0)
  • 2020-11-27 15:35

    JSON has nothing to do with jQuery.

    There is nothing wrong with the code you have now.


    To store the variable mainStore, it is a variable in that json.

    You should store that json to a variable:

    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.
    
    0 讨论(0)
  • 2020-11-27 15:38

    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. $.getJSON() makes this so easy to do. 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.

    If he can't properly profile native VS jQuery, he shouldn't even be programming native code.

    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...

    0 讨论(0)
提交回复
热议问题