简体   繁体   中英

Pulling JSON data into my app using javascript from a local JSON file

I am building an application where I need to pull data from a local JSON file in my app, parse it, and generate content on my application using this data. I already read online that due to cross origin request issues, I need to host my app on a server. I have already set it up on a working local Node server. My question now really, is how do I proceed? I don't have a lot of experience making XMLhttp requests, do I just pass my request the file path to the local JSON file? I would like the callback function just to console log some of the data at first, just so I know that it's working. Also, I want to try this out first using just plain javascript, no libraries or frameworks (I used Express, but just for the server), any help or nudge in the right direction would be greatly appreciated. Thanks!

Making XMLhttp requests from javascript is not different than requesting a web page in a browser, ie. you have to use an URL, not a file path.

var x = new XMLHttpRequest();
x.open('/file.json');
x.onreadystatechange = function(){
    if(x.readyState == 4){
        callback(x.responseText);
    }
};
x.send();

function callback(resp){
    console.log(resp);
}

here you still need to do more stuff for cross-browser

Hope this helps you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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