This article illustrates how JavaScript skillfully assembles form entries into JSON objects using the Eval function. Share to everyone for your reference, specific as follows:
When you do Web development in Ajax, you often encounter scenarios where you can save, collect form entries, compose JSON objects, and then post objects directly to the server.
The usual practice is to write code similar to the following in JS:
var myobj = {};
myobj.x = document.getElementById ("x"). Value;
MYOBJ.Y = document.getElementById ("y"). Value;
//...
Then Ajax post or get commits
When the table cell is not much, this is fine, but if a form has dozens of or more entries, writing this code will be too laborious.
The good news is that there's an evil eval function in JavaScript that can help us do some of the work like C # reflection, like the following:
Eval (' a={} ');
if (a.b==undefined)
{
a.b = {};
}
Eval (' A.B.C = 1 ');
alert (A.B.C);
In this way, we create a composite object a dynamically, understand the principle, you can make some improvements to the form:
Waybill Number: <input type= "text" name= "Awbpre" value= "112" style= "width:40px"/>-<input type= "text" name= "AwbNo" value= "12312311"/><br/> settlement method: <select name= "Settlementmode" style= "width:100px" > <option value= "CASH"
Selected= "Selected" > Cash </option> <option value= "MONTH" > Monthly junction </option> </select> <br/> Properties that do not need to be assigned: <input type= "input" name= "Notme value=" Notme ... "ismodel=" false "/> <script type=" Text/javascript "
> Function Setformmodel (modelname) {eval (modelname + "={}");
var Inputarr = document.getElementsByTagName ("INPUT");
for (Var i=0;i<inputarr.length;i++) {var Ismodel = Inputarr[i].getattribute ("Ismodel");
var itemname = Inputarr[i].name;
var itemvalue = Inputarr[i].value;
if (ismodel!= "false") {eval (modelname + ") + itemname +" = ' "+ itemvalue +" '; ");
} var Selectarr = document.getElementsByTagName ("select"); for (Var i=0;i<selectarr.length;i++) {var Ismodel = selectarr[i].getattrIbute ("Ismodel");
var itemname = Selectarr[i].name;
var itemvalue = Selectarr[i].value;
if (ismodel!= "false") {eval (modelname + ") + itemname +" = ' "+ itemvalue +" '; ");
} return modelname;
} setformmodel ("Awbmodel"); Alert ("Dan Hao:" + awbmodel.awbpre + "-" + awbmodel.awbno + "\ N) Settlement method:" + Awbmodel.settlementmode + "\ n" \ \ \ \ \ \ \ \ \ \ \ awbmodel.notme)
;
</script>
So, as long as the Name property of the form element is set correctly and you need to collect the form object, call the Setformmodel function, and you can quickly get a JSON object (which is just an example of the first-level attribute, and if you have multilevel attributes, you expand it yourself, Nothing more than a string of articles.
I hope this article will help you with JavaScript programming.