user.json文件的数据
{
"star_male": [
{
"name": "张三",
"age": 26
},
{
"name": "李四",
"age": 29
},
{
"name": "王五",
"age": 31
}
]
}
1、使用fetch的方式去读取
<script>
fetch('./user.json').then(response => response.json()).then((data) => {
console.log(data);
})
</script>
打印出来的结果
2、使用jQuery去读取
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.3/jquery.js"></script>
<script>
// 1、第一种方式(用get的方式)
$.get('./user.json').then((data) => {
console.log(data);
})
// 1、第二种方式(用getJSON的方式)
$.getJSON('./user.json').then((data) => {
console.log(data);
})
</script>
3、jsonp的方式读取(读取本地JSON文件是不会产生跨域问题,但是需要在json数据外包一个函数)
//user.json文件的数据
/* dataJSON({
"star_male": [
{
"name": "张三",
"age": 26
},
{
"name": "李四",
"age": 29
},
{
"name": "王五",
"age": 31
}
]
}) */
<script>
function dataJSON(data) {
console.log(data);
}
</script>
//注意一定要把读取函数写在前面,读取JSON文件写在后
<script src="./user.json?cb=dataJSON"></script>