纯前端内容,总结了三种json文件的格式,以及对应的ajax读取方法。
首先说明我的路径格式:jQuery、js和json是同级的
【jsonfile01.json】文件
{
"name":"Henry",
"age":5,
"sex":"male"
}
【jsonfile02.json】文件
{
"sales":{
"good":["电视","冰箱","洗衣机"],
"count":[20,15,22]
}
}
【jsonfile03.json】文件
{
"sales" : [
{"name":"苹果", "value":20},
{"name":"香蕉", "value":15},
{"name":"猕猴桃","value":18 }
]
}
下面是具体的ajax内容(具体内容因为是测试加上了注释,大家在使用的时候去掉注释就可以了)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="../../js/jquery-3.4.1.min.js"></script>
</head>
<body>
<script>
$(function(){
$.ajax({
//访问jsonfile01.json
/* url:"../../json/jsonfile01.json",
type:"get",
dataType:"json", //返回数据格式为json
success:function(data){
//console.log(data);
var stuStr = JSON.stringify(data); //对象转为字符串
document.write(stuStr);
} */
//访问jsonfile02.json
/* url:"../../json/jsonfile02.json",
type:"get",
dataType:"json",
success:function(data){
$.each(data.sales,function(key,value){
var str = '<div>'+ key +' :'+ value +'</div>';
document.write(str);
});
} */
//访问jsonfile03.json
/* url:"../../json/jsonfile03.json",
type:"get",
dataType:"json",
success:function(data){
$.each(data.sales,function(index,item){
var str = '<div>商品:'+item.name+' ,销量:'+item.value+'</div>';
document.write(str);
});
} */
});
});
</script>
</body>
</html>