m1711
m1711

Reputation: 111

How do i load my local json file just using JavaScript

My json file looks like this

{
    "Persons": {
        "Name" : "e",
        "Name2": "e",
        "Id": "4700"
    }, [...]
}

How does my code looks like to parse/load this local json file into a html file. I tried everything out but none of them worked.

Upvotes: 8

Views: 6367

Answers (1)

Sean Kendle
Sean Kendle

Reputation: 3609

Here's an example from (http://youmightnotneedjquery.com/)

request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400){
    // Success!
    data = JSON.parse(request.responseText);
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

Your data variable will then have accessible members like this:

alert(data.Persons.Name);

Upvotes: 6

Related Questions