zl程序教程

您现在的位置是:首页 >  前端

当前栏目

javascript:json数据的页面绑定示例代码

JavaScript数据JSONJSON代码 示例 页面 绑定
2023-06-13 09:15:16 时间

web开发中,如果需要将“服务端返回的json对象”绑定到“现有页面上的dom元素”,传统赋值的方式太繁琐,写起来也很累(特别是json对象很大时),于是想出了下面的偷懒方法,不过有二个前提:

1、元素的id要与json对象中的属性命名一致
2、json对象中的属性名,最好不要重复

复制代码代码如下:

<!doctypehtml>
<html>
<head>
<title>json对象遍历演示</title>
<scripttype="text/javascript">
varobj={a:"a1",b:"b1",c:{c1:"c1"},d:1,e:true,f:newDate("2012/12/24")};

//showJsonProperty(obj);
/*
functionshowJsonProperty(jsonObj){
 for(varoinjsonObj){  
  alert("属性名:"+o.toString()+",值:"+jsonObj[o].toString()+",type:"+typeof(jsonObj[o])); 
  if(typeof(jsonObj[o])=="object")
  {
   showJsonProperty(jsonObj[o]);
  }  
 }
}
*/

functionbindJson(jsonObj){
 for(varoinjsonObj){ 
  vardomObj=document.getElementById(o.toString());
  if(domObj!=undefined){
   domObj.value=jsonObj[o].toString();
  }  
  if(typeof(jsonObj[o])=="object")
  {
   bindJson(jsonObj[o]);
  }  
 }
}
functionbindData(){ 
 bindJson(obj);
}
</script>
<styletype="text/css">
 input{width:80px;height:18px;margin:010px00;border:1px#999solid}
 input:hover{border:1px#ff0000solid}
 input[type=button]{background-color:#efefef;height:22px;}
</style>
</head>
<body>
 <div>
  a:
  <inputid="a"/>
  b:
  <inputid="b"/>
  c.c1:
  <inputid="c1"/>
  d:
  <inputid="d"/>
  e:
  <inputid="e"/>
  f:
  <inputid="f"/>
  <inputtype="button"value="绑定"id="btnBind"onclick="bindData()"/>
 </div>
</body>
</html>