在jQuery中我们可以使用jQuery.getJSON()方法很方便的异步从后台获取json格式的数据。(当然也可以使用jQuery.get(),jQuery.post(),jQuery.ajax()方法返回json格式数据,)
下面引用的是官方API对$.getJSON()的说明:
jQuery.getJSON( url, [data,] [success(data, textStatus, jqXHR)] )
urlA string containing the URL to which the request is sent.
dataA map or string that is sent to the server with the request.
success(data, textStatus, jqXHR)A callback function that is executed if the request succeeds.
回调函数中接受三个参数,第一个书返回的数据,第二个是状态,第三个是jQuery的XMLHttpRequest,后面俩个参数可以省略,一般我们只使用到第一个参数,即返回值。
JQuery中使用方法是$.each()来遍历json对象:关于$.each()的详细介绍可以点击看这里
$.each()是用来在回调函数中解析JSON数据的方法,
语法:jQuery.each( collection, callback(indexInArray, valueOfElement) )
$.each()方法接受两个参数,第一个是需要遍历的对象集合(即JSON对象集合),第二个是用来遍历的方法(即对解析后的数据做处理),这个方法又接受两个参数,第一个是遍历的index(如果是json对象,则是json的key值),第二个是当前遍历的值。
比如现在后台返回json(包含了嵌套和数组):
{"user":"王某某","age":20,"addr":{"city":"厦门市","street":"博物馆"},"tel":["1865010","1516003"],"lover":"secret2","friend":[{"name":"person1"},{"name":"person2"}]}
可以在js中这样解析:(不知道为什么在显示时排版变的很难看,凑合着看吧)
function testGetJson(){
var jqxhr = $.getJSON("../jQuery!getTest.action",{"name":"wzj"},function(jsonDate){ //返回JQXHR 可以,跟$.ajax()一样调用返回失败或成功时的回调函数
//var jsonDate = eval("("+data+")");//如果返回是不是json格式,而是字符串格式,需要使用eval转为json,在get(),post(),ajax()中没有指定返回类型时,需要这一步操作
$.each(jsonDate,function(key,value){
if(key!="addr"&&key!="friend"){
$("#content").append(key+"="+value+";<hr>");
}
});
$.each(jsonDate.addr,function(key,value){//嵌套json处理,取出jsonDate.addr进行单独处理
$("#content").append(key+"="+value+";");
});
$("#content").append("<hr>friend:<br>");
$.each(jsonDate.friend,function(index,item){//对数组的处理
$("#content").append(item.name+"<br>");
});
});
jqxhr.fail(function(){alert("fail")});//请求失败时的回调函数 jqXHR.success()
, jqXHR.error()
, 在jQuery1.8 已经过时了,被fail()done()代替
jqxhr.done(function(){alert("success")});//请求成功时的回调函数
}
输出的结果(请求成功的情况下):(会弹出对话框“success”)