獲取JSON數據,在jQuery中有壹個簡單的方法 $.getJSON() 可以實現。
下面引用的是官方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,我們只使用到第壹個參數。
$.each()是用來在回調函數中解析JSON數據的方法,下面是官方文檔:
jQuery.each( collection, callback(indexInArray, valueOfElement) )
collectionThe object or array to iterate over.
callback(indexInArray, valueOfElement)The function that will be executed on every object.
$.each()方法接受兩個參數,第壹個是需要遍歷的對象集合(JSON對象集合),第二個是用來遍歷的方法,這個方法又接受兩個參數,第壹個是遍歷的index,第二個是當前遍歷的值。哈哈,有了$.each()方法JSON的解析就迎刃而解咯。
function?loadInfo()?{ $.getJSON("loadInfo",?function(data)?{ $("#info").html("");//清空info內容 $.each(data.comments,?function(i,?item)?{ $("#info").append("<div>"?+?item.id?+?"</div>"?+?"<div>"?+?item.nickname+?"</div>"?+ "<div>"?+?item.content?+?"</div><hr/>"); });});
}