如何用Ajax读取本地JSON文件呢?

一、创建一个文件夹
里面放一个json文件,写一些数据进去,例如这样的数据:

[
    {
        "username" : "zhangsan",
        "age" :23,
        "sex":"男"
    },{
        "username" : "lisi",
        "age" :24,
        "sex":"男"
    },{
        "username" : "wangwu",
        "age" :25,
        "sex":"男"
    },{
        "username" : "zhaoliu",
        "age" :26,
        "sex":"女"
    },{
        "username" : "sunqi",
        "age" :27,
        "sex":"男"
    },{
        "username" : "李狗蛋",
        "age" :28,
        "sex":"男"
    },{
        "username" : "二狗子",
        "age" :30,
        "sex":"男"
    }
]

然后再创一个index.js文件,用来写js代码,代码如下:

<!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>
</head>
<body>
    <button>获取json文件内容</button>
    <script src="https://cdn.bootcdn/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        // $.getJSON("json文件所在路径", function( res ){ });

        $("button").click(function(){
            $.getJSON("./data.json", function( res ){
                console.log( res );
            });
        });
    </script>
</body>
</html>

二、鼠标右键用Live Server打开:

注意,如果没有这个选项,那就在安装一个Live Server插件,我这里用的是vscode,如下是安装方法:

用Live Server打开后自动跳到默认浏览器中,运行效果如下:

好啦,以上就是本期内容,如果还有疑问的小伙伴请在下方留言。

更多推荐

Ajax读取本地json文件