在html中使用json文件中的数据
在html中使用json文件中的数据
<!DOCTYPE html><html><head><meta charset="utf-8"><title>json数据处理</title></head><body><script>function getJson(jsonName) {const promise = new Promise((resolve, reject) => {const xhr = new XMLHttpRequest();xhr.open('GET', jsonName);xhr.send();xhr.onreadystatechange = function() {if (xhr.readyState === 4) {//判断响应状态码 2xxif (xhr.status >= 200 && xhr.status < 300) {//控制台输出响应体const data = JSON.parse(xhr.responseText);console.log("成功");resolve(data);} else {//控制台输出响应状态码console.log("失败");console.log(xhr.status);reject(xhr.status);}}};});return promise};//json文件map.json和当前html文件在同一个目录中const jsonStr = getJson("map.json");jsonStr.then(value => {//打印json数据console.log(value);}, reason => {console.log(reason)});</script></body></html>