vscode 使用javascript获取本地json文件

本文介绍了如何在VSCode中利用JavaScript本地读取JSON文件并进行列表展示。遇到的主要问题是由于跨域限制,尝试了使用jQuery和HTML5 Files API的解决方案。最终采用的是结合VSCode的Live Server插件,通过设置允许CORS来实现本地文件的读取和显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vscode 使用javascript获取本地json文件

文件包含:

  • data.json
  • index.html
    需要实现的功能为本地读取json文件,进行列表展示

遇到问题:

使用jQuery请求本地的json文件
在script标签中引入JQuery

  • 方案1:
  $.getJSON("data.json", function (data) {
             console.log(data[first]);
         });
  • 产生跨域
    在这里插入图片描述
  • 产生原因

So when you call $.getJSON() you are actually executing an GET call as described in the JQuery docs here. https://api.jquery.com/jQuery.getJSON/ Because of that the browser will enforce CORS, even if you are using the file protocol.

在这种情况下实际是一个get请求

  • 解决方案:
    使用HTML5的Files API
    API文档-readAsText()
    然后再JSON.parse()

  • 方案2:
    使用ajax请求+vscode插件live server

  • 解决方案:
    临时:使用vscode自带的live server
    插件安装完成后,右键需要打开的html文件会有Open With Live Server
    最终:服务器这里允许CORSAccess-Control-Allow-Origin: *

最终代码如下:

  • data.json
{
  "first":[
    {"name":"张三","sex":"男"},
    {"name":"李四","sex":"男"},
    {"name":"王武","sex":"男"},
    {"name":"李梅","sex":"女"}
]
  }
  • index.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>

<body>
    <div id ="listShow"></div>
<script>
    var Ajax = function () {
        //在vscode环境这个获取本地json文件中的数据
        //可以使用vscode中的live server插件解决跨域问题
        //ajax请求可以通过引入jquery进行调用
        $.ajax({
            url: "data.json",
            type: "GET",
            success: function (res) {
               data = res["first"];
                var str = "<table>";
                for (var index in data) {      
                    str += "<tr><td>" + data[index].name + "</td><td>" + data[index].sex + "</td></tr>";
                };
                str += "</table>";
                document.getElementById("listShow").innerHTML = str;
            },
            error: function (res) {
                console.log("发生错误");
                console.log(res);
            }
        })
    }
    Ajax();
</script>

</html>

最终效果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值