jQuery读取JSON数据时,格式可以多种类型的,使用getJSON()方法,同时URL还可以是其他网站的地址文件,读取后通过分解JSON文件的内容组织为自己想要的内容,下面是网络查找到一个简单实例,其他的都和这个大同小异。
JsonJson.html文件:
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"" http://www.w3.org/TR/html4/strict.dtd " > <html > <head > <meta http - equiv = "Content-Type"content = "text/html; charset=iso-8859-1" > <title > Json Document < /title>
<script type="text/javascript " src="lib / jquery / jquery - 1.3.2.js "></script>
<script type="text / javascript ">
$(function(){
$("#button ").click(function(){
$.getJSON( b.json ,function(data){ // getJSON方法获得json文件的代码,其中的回调函数的参数data就是json代码
$("#json ").empty(); //清空带“json” ID的div标签的内容
$.each(data,function(entryIndex,entry){ //each方法遍历json文件中的对象,entryIndex是当前索引, entry是当前项
var html=" < div class = entry > ";
html += " < h3 class = term > "+entry[ term ]+ </h3> ;
html += " < div class = part > "+entry[ part ]+" < /div>";
html += "<div class= definition >"+entry[ definition ];
if(entry[ quote ]){
html+="<div class= quote >";
$.each(entry[ quote ],function(quoteIndex,line){
html+="<p>"+line+"</p > ";
});
html+=" < /div>";
}
html+="</div > ";
html +=" < /div>";
$("#json").append(html);
});
});
});
});
</script > </head>
<body>
<div id="button"><b>Get Json Document</b > </div>
<div id="json"></div > </body>
</html >
b.json文件:
[{
"term": "BACCHUS",
"part": "n.",
"definition": "A convenient deity invented by the ancients as an excuse for getting drunk.",
"quote": ["Is public worship,then,a sin.", "That for devotions paid to Bacchus", "The lictors dare to run us in.", "And resolutely thump and whack us?"],
"author": "Jorace"
},
{
"term": "BACKBITE",
"part": "v.t.",
"definition": "To speak of a man as you find him when he can t find you."
},
{
"term": "BEARD",
"part": "n.",
"definition": "The hair that is commonly cut off by those who justly execrate the absurd Chinese custom of shaving the bead."
}]
评论列表: