计科知识库
  • 源界面
  • 博客圈
  • 专题
  • 博友
  • 登录
  • 注册
源界面 源界面 1个月前

在html中使用json文件中的数据

js

在html中使用json文件中的数据
4TS3BUUh

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>json数据处理
  6. </title>
  7. </head>
  8. <body>
  9. <script>
  10. function getJson(jsonName) {
  11. const promise = new Promise((resolve, reject) => {
  12. const xhr = new XMLHttpRequest();
  13. xhr.open('GET', jsonName);
  14. xhr.send();
  15. xhr.onreadystatechange = function() {
  16. if (xhr.readyState === 4) {
  17. //判断响应状态码 2xx
  18. if (xhr.status >= 200 && xhr.status < 300) {
  19. //控制台输出响应体
  20. const data = JSON.parse(xhr.responseText);
  21. console.log("成功");
  22. resolve(data);
  23. } else {
  24. //控制台输出响应状态码
  25. console.log("失败");
  26. console.log(xhr.status);
  27. reject(xhr.status);
  28. }
  29. }
  30. };
  31. });
  32. return promise
  33. };
  34. //json文件map.json和当前html文件在同一个目录中
  35. const jsonStr = getJson("map.json");
  36. jsonStr.then(value => {
  37. //打印json数据
  38. console.log(value);
  39. }, reason => {
  40. console.log(reason)
  41. });
  42. </script>
  43. </body>
  44. </html>
  • © 2025 源界面 源码为笔,博客为路,写就数字未来
  • 建议
  • 图片压缩
  • | 鄂ICP备14016484号-6

    鄂公网安备 42068402000140