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>
<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")};

function bindJson(jsonObj){
 for(var o in jsonObj){ 
  var domObj = document.getElementById(o.toString());
  if (domObj!=undefined){
  if (typeof(jsonObj[o])=="object")
function bindData(){ 
<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 id="a" />
  <input id="b" />
  <input id="c1" />
  <input id="d" />
  <input id="e" />
  <input id="f" />
  <input type="button" value=" The binding " id="btnBind" onclick="bindData()"/>

Related articles: