如何用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.net/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打开:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。