1项目中用到springmvc,@Responsebody返回数据,当返回实体类时,比如User,此时User是json格式的字符窜,需要用eval来转换成json
在JS中,把 json 格式的字符串转成JSON对象,关键代码
json = eval('('+str+')');
方法如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JSON应用</title>
<script type="text/javascript">
function StrToJSON(str) {
json = eval('('+str+')');
return json;
}
function ToJSON(data) {
json = eval(data);
return json;
}
// JSON数据
str = '{id:1,title:"你好,朋友",addtime:"2010-05-03"}';
strJson = StrToJSON(str);
data = {id:2,title:"你好,哈哈",addtime:"2010-05-04"};
Json = ToJSON(data);
document.write(strJson.id+"、 "+strJson.title+" "+strJson.addtime+"<br />");
document.write(Json.id+"、 "+Json.title+" "+Json.addtime+"<br />");
</script>
</head>
<body>
</body>
</html>
2当返回数据不是实体类时,是一些List<Object[]>集合,
比如
String sql="select u.loginName,u.picurl from users u ";
List<Object[]> users=userDaoI.findBySql(sql);
$.each(data,function(i,item))
此时返回的集合访问直接用数组下表,比如要访问loginName,就item[0],picurl就item[1],以此类推
3下面介绍几种常用遍历json的方法
grep //筛选json
<script type='text/javascript' src="/jquery.js"></script>
<script type="text/javascript">
$().ready(
function(){
var array = [1,2,3,4,5,6,7,8,9];
var filterarray = $.grep(array,function(value){
return value > 5;//筛选出大于5的
});
for(var i=0;i<filterarray.length;i++){
alert(filterarray[i]);
}
for (key in filterarray){
alert(filterarray[key]);
}
}
);
</script>
each //当有多个标签需要循环赋值时,用each比较好,比如给类选择器赋值时,类选择器一般对应多个标签
<script type='text/javascript' src="/jquery.js"></script>
<script type="text/javascript">
$().ready(
function(){
var anObject = {one:1,two:2,three:3};//对json数组each
$.each(anObject,function(name,value) {
alert(name);
alert(value);
});
var anArray = ['one','two','three'];
$.each(anArray,function(n,value){
alert(n);
alert(value);
}
);
}
);
</script>
inArray //返回某一特定值
<script type='text/javascript' src="/jquery.js"></script>
<script type="text/javascript">
$().ready(
function(){
var anArray = ['one','two','three'];
var index = $.inArray('two',anArray);
alert(index);//返回该值在数组中的键值,返回1
alert(anArray[index]);//value is two
}
);
</script>
map
<script type='text/javascript' src="/jquery.js"></script>
<script type="text/javascript">
$().ready(
function(){
var strings = ['0','1','2','3','4','S','6'];
var values = $.map(strings,function(value){
var result = new Number(value);
return isNaN(result) ? null:result;//isNaN:is Not a Number的缩写
}
);
for (key in values) {
alert(values[key]);
}
}
);
</script>
遍历json对象:
<script>
var json = [{dd:'SB',AA:'东东',re1:123},{cccc:'dd',lk:'1qw'}];
for(var i=0,l=json.length;i<l;i++){
for(var key in json[i]){
alert(key+':'+json[i][key]);
}
}
</script>
遍历json对象
有如下 json对象:
var obj ={”name”:”冯娟”,”password”:”123456″,”department”:”技术部”,”sex”:” 女”,”old”:30};
遍历方法:
for(var p in obj){
str = str+obj[p]+’,';
return str;
}