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

How do i load my local json file just using JavaScript

本文关键字:json 文件 我的 加载 何仅使 JavaScript      更新时间:2023-09-26

我的 json 文件看起来像这样

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

我的代码如何解析/加载此本地 json 文件到 html 文件中。我尝试了所有方法,但没有一个奏效。

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