When Ajax is used for web development, it is often used to collect form input items before saving them to form a JSON object, and then directly post the objects to the server.
The general practice is to write the following code in JS:Code:
VaR myobj = {}; myobj. X = document. getelementbyid ("X "). value; myobj. y = document. getelementbyid ("Y "). value ;//... // then submit Ajax post or get
This is fine when there are not many form elements, but if a form has dozens or even more input items, it is too hard to write this code.
Fortunately, there is an evil eval function in Javascript, which can help us do something similar to C # reflection, such as the following:
Eval ('a ={} '); if (. B = undefined) {. B ={};} eval ('a. b. C = 1'); alert (. b. c );
In this way, we dynamically create a composite object A. After understanding the principle, we can make some improvements to the form:
Waybill No: <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 settlement </option> </SELECT> <br/> attributes that do not need to be assigned values: <input type = "input" name = "notme" value = "notme... "ismodel =" false "/> <SCRIPT type =" text/JavaScript "> function setfo Rmmodel (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 (" Ticket No.: "+ awbmodel. awbpre + "-" + awbmodel. awbno + "\ n settlement method:" + awbmodel. settlementmode + "\ n attributes not available:" + awbmodel. notme); </SCRIPT>
in this way, when the name attribute of the form element is correctly set and the form object needs to be collected, call the setformmodel function to quickly obtain a JSON object (of course, this is just an example, only the first-level attribute is processed. If there is a multi-level attribute, you can expand it by yourself. It is nothing more than doing some articles on the string)