• Coding: Testing To Fetch JSON Data Using XMLHttpRequest()

     

    Coding Testing by Bryan Granse Devs
    JAVASCRIPT FETCHING JSON USING XMLHttpRequest()

    Index.html I have this basic HTML that will use to display data from JSON file, here is the code below.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Javascript Fetch JSON FILE</title>
        <link rel="shortcut icon" href="data:" type="image/x-icon">
    </head>
    <body>
        <div class="output"></div>
        <script src="./app.js"></script>
    </body>
    </html>
    App.js is where the JavaScript magic happens to fetch the JSON file.

    const url = './data.json'; 
    const output = document.querySelector('.output'); 
     let xHR = new XMLHttpRequest(); 
     console.log(xHR) 
    xHR.open('GET', url); 
    xHR.responseType = 'json'; 
    xHR.onload = function() {     
    console.log(xHR.response);     
    let data = xHR.response;     
    data.books.forEach(result => {         
    output.innerHTML += `§{result.title}<br />`;     
    }) } 
    xHR.send(); console.log(xHR);

    Below is the JSON file that I use, you can create your own and explore, this is just for testing that will let us display data using XML http request.

    {
        "books": [
            {
                "title": "Learn to Code",
                "author": "Bryan Devs",
                "isbn": "324-23243"
            },
            {
                "title": "The Adventure JSON",
                "author": "Jason Jones",
                "isbn": "3324-2-444"
            },
            {
                "title": "New Objects",
                "author": "Jane Doe",
                "isbn": "2343-234-2433"
            }

        ]
    }

    If you want to get the source code file you can visit this site PH Directories & Resources and download the whole file cheers.
  • 0 comments:

    Post a Comment

    GET A FREE QUOTE NOW

    I am flexible and would like to work with you long term, and currently I am looking for a fulltime job with a long term opportunity, but able to work also part-time, get free qoute for project.

    Search This Blog

    Powered by Blogger.

    Mga Pahina

    ADDRESS

    Purok 5-A, Brgy. Magdum, Tagum City 8100, Davao del Norte, Philippines

    EMAIL

    gransebryan@gmail.com
    bryanworkdevs@gmail.com