利⽤jquery如何从json中读取数据追加到html中JSON 格式
json 是 Ajax 中使⽤频率最⾼的数据格式,在浏览器和服务器中之间的通讯可离不开它。
JSON 格式说明
需要特别注意的是,在 JSON 中的属性名是需要使⽤引号引起来的。
1.下载安装jquery
可通过下⾯的⽅法引⼊在线版本的js:
<script src="apps.bdimg/libs/jquery/2.1.4/jquery.min.js"></script>
2.准备⼀个json格式的⽂件,后缀可以不是.json
例如下⾯是result.json的格式
{
"title":"【UI测试结果】-转转2017/1/23 14:47",
"starttime":"2017/1/23 15:00 45",
"endtime":"2017/1/23 15:01 42",
"passcount":10,
"failurecount":5,
"resultinfo":[
{
"name":"发布",
"moudle":"Publish",
"pass":"true",
"onecepass":"true",
"log":"true"
},
{
"name":"登录",
"moudle":"Login",
"pass":"false",
"onecepass":"true",
"log":"asserterrorlog",
"failurereason":{
"errorlog":"asserterror",
"errorimg":"./登录.jpg"
}
}
]
}
3.通过$.getJSON获得Json⽂件的数据
es8例如下⾯的例⼦:读取result.json⽂件的内容,存储到result变量中,结果是⼀个json格式
$.getJSON('./result.json',function(result){}
4.通过【$('#元素id').after(html内容);】将html内容添加到定位到的元素后⾯
元素定位⽅式
$("#id"):定位到id,
$(“p"):定位到标签p,其他标签同理
$(“.class”):定位到class
插⼊html内容位置:
append() - 在被选元素的结尾插⼊内容
prepend() - 在被选元素的开头插⼊内容
jquery下载的文件怎么使用after() - 在被选元素之后插⼊内容
before() - 在被选元素之前插⼊内容
Json数据的操作
JSON对象[key]来读取内容:result['title'],或者⽤result.”title"
数组的对象值,可以通过$.each来获得数据:
$.each(JSON数组对象,function(遍历索引i,遍历对象){操作遍历的对象})
读取result.json,追加html的代码如下
(jquery需要写在<script>标签内)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
asp和aspnet有什么区别<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<script src="apps.bdimg/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
//使⽤getJSON⽅法读取json数据,
设置combobox的内容//注意:info.json可以是不同类型⽂件,只要其中的数据为json类型即可
$.getJSON('./result.json',function(result){
var html_title='';
var html_resultinfo='';
html_title += '<b>'+result["title"]+'</b>';
$('#resultitle').after(html_title);
$.each(result["resultinfo"],function(i,item){
if(item["pass"]=="true") {
html_resultinfo += '<tr><td>' + item['name'] + '</td>' +
'<td>' + item['moudle'] + '</td>' +
'<td>' + item["pass"] + '</td>' +
'<td>' + item['onecepass'] + '</td>' +
'<td id="' + item['moudle'] + '" class="collapsed" onclick="collapsedisplay(' + item['moudle'] + ')"><u >展开</u></td></tr>';
html_resultinfo +='<tr id="' + item['moudle'] + 'info" class="collapsedinfo" ><td colspan="5">' + item['log'] + '</td></tr>';
}
$('#infotitle').after(html_resultinfo);//after⽅法:在每个匹配的元素之后插⼊内容。
});
});
</script>
</HEAD>
<BODY>
<div >
<div >
<p id="resultitle" ></p>
</div>
</div>
<div id="resultinfo" >
<table >
<tr id="infotitle">
<th >⽤例名称</th>
<th >模块名称</th>
<th >是否成功</th>
<th >⼀次成功</th>
<th >详情</th></tr>
</table>
软件编程前端和后端</div>
</div>
</BODY>
</HTML>双老太婆怎么死的
总结
以上就是这篇⽂章的全部内容了,希望本⽂的内容对⼤家的学习或者⼯作具有⼀定的参考学习价值,如果有疑问⼤家可以留⾔交流,谢谢⼤家对的⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。