PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 23, 2022

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

 July 23, 2022     javascript, json, xmlhttprequest     No comments   

Issue

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 an object in JavaScript?

This is for example my JSON file located at ../json/main.json:

{"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]}

and i want to use it in my table.js file like this:

for (var i in mainStore)
{       
    document.write('<tr class="columnHeaders">');
    document.write('<td >'+ mainStore[i]['vehicle'] + '</td>');
    document.write('<td >'+ mainStore[i]['description'] + '</td>');
    document.write('</tr>');
} 

Solution

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


Answered By - Drew Noakes
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing