jquery解析json怎么解析

 我来答
Baby_原來
2017-07-19 · TA获得超过3401个赞
知道大有可为答主
回答量:1535
采纳率:94%
帮助的人:479万
展开全部

获取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/>");        
         });        
    });
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式