jQuery中讀取json檔案範例程式碼

來源:互聯網
上載者:User

json檔案是一種輕量級的資料互動格式。一般在jquery中使用getJSON()方法讀取。
複製代碼 代碼如下:
$.getJSON(url,[data],[callback])

url:載入的頁面地址
data: 可選項,發送到伺服器的資料,格式是key/value
callback:可選項,載入成功後執行的回呼函數
1.首先建一個JSON格式的檔案userinfo.json 儲存使用者資訊。如下:
複製代碼 代碼如下:
[
{
"name":"張國立",
"sex":"男",
"email":"zhangguoli@123.com"
},
{
"name":"張鐵林",
"sex":"男",
"email":"zhangtieli@123.com"
},
{
"name":"鄧婕",
"sex":"女",
"email":"zhenjie@123.com"
}
]

2.其次建一個頁面用於擷取JSON檔案裡的使用者資訊資料,並顯示
複製代碼 代碼如下:
<!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>getJSON擷取資料</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<style type="text/css">
#divframe{ border:1px solid #999; width:500px; margin:0 auto;}
.loadTitle{ background:#CCC; height:30px;}
</style>
<script type="text/javascript">
$(function(){
$("#btn").click(function(){
$.getJSON("js/userinfo.json",function(data){
var $jsontip = $("#jsonTip");
var strHtml = "123";//儲存資料的變數
$jsontip.empty();//清空內容
$.each(data,function(infoIndex,info){
strHtml += "姓名:"+info["name"]+"<br>";
strHtml += "性別:"+info["sex"]+"<br>";
strHtml += "郵箱:"+info["email"]+"<br>";
strHtml += "<hr>"
})
$jsontip.html(strHtml);//顯示處理後的資料
})
})

})
</script>
</head>
<body>
<div id="divframe">
<div class="loadTitle">
<input type="button" value="擷取資料" id="btn"/>
</div>
<div id="jsonTip">
</div>
</div>
</body>
</html>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.