本文实例采用案例分析的方法介绍了jquery遍历json对象的三种情况,供大家参考,具体内容如下
第一个案例:
jsp中
}else{
$.each(jsonText,function(i,item){
var pngPath = item[0];
var pngName = item[1];
});
}
}
}
});
jsonText的格式:
java中:
0) {
JSONArray pngFileArray =JSONArray.fromObject(pngFileList);
}
if(null != pngFileArray){
this.setTextAjax(pngFileArray.toString());
//异常的格式
//this.setTextAjax("{\"status\":\"500\",\"msg\":\""+errormsg+"\"}");//没有记录
/**
- ajax返回html,包括json形式
-
- @param responseContent
*/
public void setTextAjax(String responseContent) {
try {
HttpServletResponse response = getHttpResponse();
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.setHeader("Pragma","No-cache");
response.setHeader("Content-Type","text/html");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires",0);
PrintWriter out = response.getWriter();
out.print(responseContent);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
// ajaxResponse = new StringBufferInputStream(responseContent);
}
第二个案例:
jQuery 遍历JSON 对象
}else{
$.each(jsonText,function(i,item){
var pngPath = item[0];
var pngName = item[1];
});
}
}
}
});
}
if(null != pngFileArray){
this.setTextAjax(pngFileArray.toString());
//异常的格式
//this.setTextAjax("{\"status\":\"500\",\"msg\":\""+errormsg+"\"}");//没有记录
/**
- ajax返回html,包括json形式
- @param responseContent
*/
public void setTextAjax(String responseContent) {
try {
HttpServletResponse response = getHttpResponse();
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.setHeader("Pragma","No-cache");
response.setHeader("Content-Type","text/html");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires",0);
PrintWriter out = response.getWriter();
out.print(responseContent);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
// ajaxResponse = new StringBufferInputStream(responseContent);
}
代码:
<script type="text/javascript">
$(document).ready(function() {
$("#Link").click(function() {
var objson = "[{Title:'Sjr',Content:'Library',summary:'summary'},{Title:'Sjr',summary:[{sum0:'sum0'},{sum0:'sum1'},{sum0:'sum2'}]},{sum0:'sum2'}]}]";
var obj = eval(objson);
$(obj).each(function(index) {
var val = obj[index];
if (typeof (val.summary) == "object") {
$(val.summary).each(function(ind) {
alert(val.Title + " " + val.Content + " " + val.summary[ind].sum0);
});
} else {
alert(val.Title + " " + val.Content + " " + val.summary);
}
});
});
});
第三个案例:
jquery中遍历读取json串中的对象获取如下的json串,其中包括数组。我们该如何遍历读取呢?
代码如下: