我们先以解析上例中的comments对象的JSON数据为例,然后再小结jQuery中解析JSON数据的方法。
上例中得到的JSON数据如下,是一个嵌套JSON:
{"comments":[{"content":"很不错嘛","id":1,"nickname":"小红"},{"content":"测试","id":2,"nickname":"小强"}]}
获取JSON数据,在jQuery中有一个简单的方法 $.getJSON() 可以实现。
下面引用的是官方API对$.getJSON()的说明:
jQuery.getJSON( url, [data,] [success(data, textStatus, jqXHR)] ) url A string containing the URL to which the request is sent. data A 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) ) collection The 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/>"); }); }); }
正如上面,loadinfo是请求的地址,function(data){...}就是在请求成功后的回调函数,data封装了返回的JSON对象,在下面的$.each(data.comments,function(i,item){...})方法中data.comments直接到达JSON数据内包含的JSON数组。
$.each()方法中的function就是对这个数组进行遍历,再通过操作DOM插入到合适的地方的。在遍历的过程中,我们可以很方便的访问当前遍历index(代码中的”i“)和当前遍历的值(代码中的”item“)。
如果返回的JSON数据比较复杂,则只需多些$.each()进行遍历即可。例如如下JSON数据:
{"comments":[{"content":"很不错嘛","id":1,"nickname":"小兰"},{"content":"看看","id":2,"nickname":"小强"}],"content":"你是木头人,哈哈。","infomap":{"性别":"男","职业":"程序员","博客":"http:\/\/www.cnblogs.com\/codeplus\/"},"title":"123木头人"}
function loadInfo() { $.getJSON("loadInfo", function(data) { $("#title").append(data.title+"<hr/>"); $("#content").append(data.content+"<hr/>"); //jquery解析map数据 $.each(data.infomap,function(key,value){ $("#mapinfo").append(key+"----"+value+"<br/><hr/>"); }); //解析数组 $.each(data.comments, function(i, item) { $("#info").append( "<div>" + item.id + "</div>" + "<div>" + item.nickname + "</div>" + "<div>" + item.content + "</div><hr/>"); }); }); }
值得注意的是,$.each()遍历Map的时候,function()中的参数是key和value,十分方便。