来自于《jquery权威指南》
--------------------------------------
点击button后,获取到json文件数据,显示如下:
Json文件:
[
{
"name":"王美丽",
"sex": "女",
"age":29
},
{
"name":"梁帅哥",
"sex": "男",
"age":30
}
]
index.html代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>jQuery</title> <style type="text/css"> body,div,ul,li,p{margin: 0;padding: 0; font-size: 13px;} ul{list-style-type: none;} .load{width: 230px;border: solid 1px #666;padding: 10px;background-color: orange;} </style> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(function(){ $("#btn").click(function(){ var strHtml = ""; $.getJSON("a.json",function(data){ //alert("aaa"); $(".load").empty(); $.each(data, function(InfoIndex, Info){ strHtml += "姓名:" + Info['name'] + "<br />"; strHtml += "性别:" + Info['sex'] + "<br />"; strHtml += "年龄:" + Info['age'] + "<hr>"; }); $(".load").html(strHtml);//出了回调函数,strhtml似乎就为空? }); }); }); </script> </head> <body> <div class="load"></div> <p><input type="button" id="btn" value="获取数据" /></p> </body> </html>
注意内容:
(1)$.getJSON 大小写问题;
(2)json数据格式书写正确。