Javascript: page binding sample code for json data

  • 2020-03-30 01:28:30
  • OfStack

In web development, if you need to bind the "json object returned by the server" to the "dom element on the existing page", the traditional method of assigning value is too tedious and tiring to write (especially when the json object is large), so you came up with the following lazy method, but with two premises:

1. The id of the element should be named the same as the attribute in the json object
2. It is best not to repeat the attribute name in the json object


<!doctype html>
<html>
<head>
<title>json Object traversal demonstration </title>
<script type="text/javascript">
var obj = {a:'a1',b:'b1',c:{c1:'c1'},d:1,e:true,f:new Date("2012/12/24")};
//showJsonProperty(obj);

function bindJson(jsonObj){
 for(var o in jsonObj){ 
  var domObj = document.getElementById(o.toString());
  if (domObj!=undefined){
   domObj.value=jsonObj[o].toString();
  }  
  if (typeof(jsonObj[o])=="object")
  {
   bindJson(jsonObj[o]);
  }  
 }
}
function bindData(){ 
 bindJson(obj);
}
</script>
<style type="text/css">
 input{width:80px;height:18px;margin:0 10px 0 0;border:1px #999 solid}
 input:hover{border:1px #ff0000 solid}
 input[type=button]{background-color:#efefef;height:22px;}
</style>
</head>
<body>
 <div>
  a:
  <input id="a" />
  b:
  <input id="b" />
  c.c1:
  <input id="c1" />
  d:
  <input id="d" />
  e:
  <input id="e" />
  f:
  <input id="f" />
  <input type="button" value=" The binding " id="btnBind" onclick="bindData()"/>
 </div>
</body>
</html>


Related articles: