admin管理员组

文章数量:1330564

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.

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.

Share Improve this question edited Jan 21, 2015 at 19:52 Sean Kendle 3,6291 gold badge29 silver badges35 bronze badges asked Dec 8, 2014 at 14:35 m1711m1711 1111 silver badge8 bronze badges 17
  • 1 You need to make an AJAX GET request to load data. Then you would use JSON.parse to parse text loaded content into object data. – dfsq Commented Dec 8, 2014 at 14:38
  • What are you using to retrieve the data? An attempt should help everyone out. – Mr. Polywhirl Commented Dec 8, 2014 at 14:39
  • @dfsq AJAX GET of the local file will fails in Chrome. – lexicore Commented Dec 8, 2014 at 14:40
  • @lexicore it should work if running a local webserver. – brbcoding Commented Dec 8, 2014 at 14:41
  • 2 @brbcoding I'd argue that "load a resource using a local webserver" is not the same as "load a local file". – lexicore Commented Dec 8, 2014 at 14:42
 |  Show 12 more ments

1 Answer 1

Reset to default 6

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

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

本文标签: ajaxHow do i load my local json file just using JavaScriptStack Overflow