欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

jQuery中使用Ajax獲取JSON格式數(shù)據(jù)示例代碼

 更新時(shí)間:2013年11月26日 16:57:53   作者:  
有時(shí)候我們需要讀取JSON格式的數(shù)據(jù)文件,在jQuery中可以使用Ajax或者 $.getJSON()方法實(shí)現(xiàn),下面有個不錯的示例,需要的朋友可以參考下
JSON(JavaScript Object Notation)是一種輕量級的數(shù)據(jù)交換格式。JSONM文件中包含了關(guān)于“名稱”和“值”的信息。有時(shí)候我們需要讀取JSON格式的數(shù)據(jù)文件,在jQuery中可以使用Ajax或者 $.getJSON()方法實(shí)現(xiàn)。

下面就使用jQuery讀取music.txt文件中的JSON數(shù)據(jù)格式信息。
首先,music.txt中的內(nèi)容如下:
復(fù)制代碼 代碼如下:

[
{"optionKey":"1", "optionValue":"Canon in D"},
{"optionKey":"2", "optionValue":"Wind Song"},
{"optionKey":"3", "optionValue":"Wings"}
]

下來是HTML代碼:
復(fù)制代碼 代碼如下:

<div>點(diǎn)擊按鈕獲取JSON數(shù)據(jù)</div>
<input type="button" id="button" value="確定" />
<div id="result"></div>

使用Ajax獲取JSON數(shù)據(jù)的jQuery代碼:
復(fù)制代碼 代碼如下:

$(document).ready(function(){
$('#button').click(function(){
$.ajax({
type:"GET",
url:"music.txt",
dataType:"json",
success:function(data){
var music="<ul>";
//i表示在data中的索引位置,n表示包含的信息的對象
$.each(data,function(i,n){
//獲取對象中屬性為optionsValue的值
music+="<li>"+n["optionValue"]+"</li>";
});
music+="</ul>";
$('#result').append(music);
}
});
return false;
});
});

當(dāng)然,也可以使用$.getJSON()方法,代碼簡潔一點(diǎn):
復(fù)制代碼 代碼如下:

$(document).ready(function(){
$('#button').click(function(){
$.getJSON('music.txt',function(data){
var music="<ul>";
$.each(data,function(i,n){
music+="<li>"+n["optionValue"]+"</li>";
});
music+="</ul>";
$('#result').append(music);
});
return false;
});
});

相關(guān)文章

最新評論