Search code examples
javascriptjsonhttpexpressxmlhttprequest

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!


Solution

  • 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 :)