首页 前端知识 如何使用js(jQuery)加载json?

如何使用js(jQuery)加载json?

2024-05-18 18:05:26 前端知识 前端哥 246 694 我要收藏

前期准备:

1.网站开发工具(这里以HBuilderX为例)

2.一台能开机的电脑

一、ajax(XMLHttpRequest):

// index.json文件
{
"data": {
"list": [
{"name": "数据表1", "id": "1"},
{"name": "数据表2", "id": "2"},
{"name": "数据表3", "id": "3"}
]
}
}
复制

html代码如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>加载json</title>
</head>
<body>
</body>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { // 当满足返回第四阶段和状态码为200时执行
var json = JSON.parse(this.responseText); //转换读取到的文件内容为json格式
console.log(json);
}
}
xmlhttp.open('GET', '/index.json'); // 导入JSON文件
xmlhttp.send();
</script>
</html>
复制

这里采用的是js里ajax的异步加载,创建XMLHttpRequest参数之后通过这个属性读取json文件,最后使用JSON.parse把读取到的JSON文件转化为json数据通过控制台输出。

 二、$.ajax()(Jquery)加载: 

注意:使用此方法之前需要引入jquery库

// 推荐cdn地址
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
复制

html代码如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>加载json</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
</body>
<script>
$.ajax({
method: "GET", // 设置请求方式为GET
url: "/index.json", // 加载本地json文件
dataType: "json", // 设置数据类型为json
success: function(e){
console.log(e); // 输出结果
}
})
</script>
</html>
复制

运行结果:

 三、$.getJSON()(jquery)加载:

注意: 这里需要jquery库

html代码如下: 

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>加载json</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
</body>
<script>
$.getJSON("/index.json", function(e){
console.log(e);
})
</script>
</html>
复制

运行结果:

 那么我们写了这么多导入JSON的方法,那如何将数据显示出来呢?

具体代码如下: (这里以第二种方法为例)

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>加载json</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<style>
* {
margin: 0;
padding: 0;
}
.here { /* 修饰div样式*/
width: 1000px;
height: 500px;
background: #00ffff;
margin: 100px auto;
}
</style>
<div class="here"></div> <!-- 我们将数据显示到这里 -->
</body>
<script>
var box = document.getElementsByClassName('here')[0]; //获取div盒子属性
var list = ''; // 设置空参数用来接收循环里输出的内容
$.ajax({
method: "GET",
url: "/index.json",
dataType: "json",
success: function(e){
let data = e.data.list; // 读取数据到数组下
for(let i=0; i<data.length; i++){ // 遍历数组读取数据
list += 'id是: ' + data[i].id + ', 名字是: ' + data[i].name + "<br>"; //将读取到的数据写入开始设置的空参数里
}
box.innerHTML = list; // 将数据输出到html界面
}
})
</script>
</html>
复制

运行结果:

 

转载请注明出处或者链接地址:https://www.qianduange.cn//article/8738.html
标签
评论
发布的文章

JQuery中的load()、$

2024-05-10 08:05:15

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!