天天看點

html ajax擷取json資料,jQuery中使用Ajax擷取JSON格式資料

JSON(JavaScript Object Notation)是一種輕量級的資料交換格式。JSONM檔案中包含了關于“名稱”和“值”的資訊。有時候我們需要讀取JSON格式的資料檔案,在jQuery中可以使用Ajax或者 $.getJSON()方法實作。

下面就使用jQuery讀取music.txt檔案中的JSON資料格式資訊。

首先,music.txt中的内容如下:

[

{"optionKey":"1", "optionValue":"Canon in D"},

{"optionKey":"2", "optionValue":"Wind Song"},

{"optionKey":"3", "optionValue":"Wings"}

]

接下來是HTML代碼:

點選按鈕擷取JSON資料

使用Ajax擷取JSON資料的jQuery代碼:

$(document).ready(function(){

$('#button').click(function(){

$.ajax({

type:"GET",

url:"music.txt",

dataType:"json",

success:function(data){

var music="";

//i表示在data中的索引位置,n表示包含的資訊的對象

$.each(data,function(i,n){

//擷取對象中屬性為optionsValue的值

music+="

"+n["optionValue"]+"";

});

music+="";

$('#result').append(music);

}

});

return false;

});

});

當然,也可以使用$.getJSON()方法,代碼簡潔一點:

$(document).ready(function(){

$('#button').click(function(){

$.getJSON('music.txt',function(data){

var music="";

$.each(data,function(i,n){

music+="

"+n["optionValue"]+"";

});

music+="";

$('#result').append(music);

});

return false;

});

});