jQuery中使用Ajax获取JSON格式数据

发布于 2011-05-17 | 更新于 2020-09-20

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;
});
});

本文作者: arthinking

本文链接: https://www.itzhai.comjquery-json-format-to-use-ajax-to-get-the-data.html

版权声明: 版权归作者所有,未经许可不得转载,侵权必究!联系作者请加公众号。

×
IT宅

关注公众号及时获取网站内容更新。