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

How can I open a JSON file in JavaScript without 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();}

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


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.