來自於《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資料格式書寫正確。