- var data="
- {
- root:
- [
- {name:'1',value:'0'},
- {name:'6101',value:'西安市'},
- {name:'6102',value:'铜川市'},
- {name:'6103',value:'宝鸡市'},
- {name:'6104',value:'咸阳市'},
- {name:'6105',value:'渭南市'},
- {name:'6106',value:'延安市'},
- {name:'6107',value:'汉中市'},
- {name:'6108',value:'榆林市'},
- {name:'6109',value:'安康市'},
- {name:'6110',value:'商洛市'}
- ]
- }";
var data=" { root: [ {name:'1',value:'0'}, {name:'6101',value:'西安市'}, {name:'6102',value:'铜川市'}, {name:'6103',value:'宝鸡市'}, {name:'6104',value:'咸阳市'}, {name:'6105',value:'渭南市'}, {name:'6106',value:'延安市'}, {name:'6107',value:'汉中市'}, {name:'6108',value:'榆林市'}, {name:'6109',value:'安康市'}, {name:'6110',value:'商洛市'} ] }";
对于服务器返回的JSON字符串,如果jquery异步请求没做类型说明,或者以字符串方式接受,那么需要做一次对象化处理,方式不是太麻烦,就是将该字符串放于eval()中执行一次。这种方式也适合以普通javascipt方式获取json对象,以下举例说明:
- var dataObj=eval("("+data+")");//转换为json对象
- alert(dataObj.root.length);//输出root的子对象数量
- $.each(dataObj.root,fucntion(idx,item){
- if(idx==0){
- return true;
- }
- //输出每个root子对象的名称和值
- alert("name:"+item.name+",value:"+item.value);
- })
var dataObj=eval("("+data+")");//转换为json对象 alert(dataObj.root.length);//输出root的子对象数量 $.each(dataObj.root,fucntion(idx,item){ if(idx==0){ return true; } //输出每个root子对象的名称和值 alert("name:"+item.name+",value:"+item.value); })
注:对于一般的js生成json对象,只需要将$.each()方法替换为for语句即可,其他不变。
JSON文件:
- [
- {
- "name":"xujun",
- "sex":"男",
- "home":"nanjing"
- },
- {
- "name":"jack",
- "sex":"男",
- "home":"beijing"
- }
- ]
[ { "name":"xujun", "sex":"男", "home":"nanjing" }, { "name":"jack", "sex":"男", "home":"beijing" } ]
Html文件:
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- <script src="../jquery.js"></script>
- <script>
- $(document).ready(function(){
- $.getJSON('jsonData.json?id',function(data){
- //遍历JSON中的每个entry
- $.each(data,function(entryIndex,entry){
- var html='<tr>';
- html+='<td>'+entry['name']+'</td>';
- html+='<td>'+entry['sex']+'</td>';
- html+='<td>'+entry['home']+'</td>';
- html+='</tr>';
- $('#title').after(html);
- });
- });
- });
- </script>
- </head>
- <body>
- <table>
- <tr id="title">
- <th>姓名</th>
- <th>性别</th>
- <th>家庭地址</th>
- </tr>
- </table>
- </body>
- </html>