如何使用JavaScript加载我的本地json文件

时间:2014-12-08 14:35:32

标签: javascript ajax serialization

我的json文件看起来像这样

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

我的代码如何将此本地json文件解析/加载到html文件中。 我尝试了一切,但没有一个工作。

1 个答案:

答案 0 :(得分:6)

以下是(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();

您的data变量将具有以下可访问成员:

alert(data.Persons.Name);