通过jquery的ajax请求本地的json文件方法

2020-05-17 06:28:18易采站长站整理

自己学习jquery的ajax的经历,记录一下

ajaxTestDemo.html

在body里面放一个id为test的div


<div id="test"></div>

第一步还是要先加载jquery文件 jquery.min.js


<script>
$(function(){
$.ajax({
//请求方式为get
type:"GET",
//json文件位置
url:"./data/shuju.json",
//返回数据格式为json
dataType: "json",
//请求成功完成后要执行的方法
success: function(data){
//使用$.each方法遍历返回的数据date,插入到id为#result中
var str="<ul>";
$.each(data.list,function(i,n){
str+="<li>"+n["item"]+"</li>";
})
str+="</ul>";
$("#test").append(str);
}
});
});
</script>

shuju.json文件


{
"list":[
{"item":"审计管理"},
{"item":"菜单管理"},
{"item":"订单管理"},
{"item":"合同管理"},
{"item":"物流管理"},
{"item":"行政管理"},
{"item":"人事管理"},
{"item":"购物管理"},
{"item":"批发管理"},
{"item":"安全管理"},
{"item":"账号管理"},
{"item":"财务管理"},
{"item":"其他管理"}
]}

/* json文件里竟然不能有这样的注释,因为困扰了几个小时!*/

完整的页面代码


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试jquey的ajax方法</title>
<style>
*{
padding:0;
margin:0;
}
#test{
padding: 0;
margin: 0 auto;
width:200px;
height: 400px;
}
#test li{
list-style: none;
width:200px;
text-align: center;
height:30px;
line-height:30px;
border:1px dashed lightgrey;
}
</style>
</head>
<body>

<div id="test"></div>
<script src="js/jquery.min.js"></script>
<script>
$(function(){
alert(1);
$.ajax({
//请求方式为get
type:"GET",
//json文件位置
url:"./data/shuju.json",
//返回数据格式为json
dataType: "json",
//请求成功完成后要执行的方法
success: function(data){
//使用$.each方法遍历返回的数据date,插入到id为#result中
var str="<ul>";
$.each(data.list,function(i,n){
str+="<li>"+n["item"]+"</li>";
})
str+="</ul>";
$("#test").append(str);
}
});
});
</script>
</body>
</html>