Home >Web Front-end >JS Tutorial >JavaScript cleverly uses the eval function to assemble form input items into json objects_javascript skills
The example in this article describes how JavaScript cleverly uses the eval function to assemble form input items into json objects. Share it with everyone for your reference, the details are as follows:
When doing web development using Ajax, you often encounter scenarios where you collect form input items to form a json object before saving, and then post the object directly to the server
The conventional approach is to write code similar to the following in js:
var myObj = {}; myObj.x = document.getElementById("x").value; myObj.y = document.getElementById("y").value; //... //然后ajax post或get提交
This is okay when there are not many form elements, but if a form has dozens or even more input items, writing this kind of code will be too laborious.
Fortunately, there is an evil eval function in JavaScript, which can help us complete some work similar to C# reflection, such as the following:
eval('A={}'); if (A.b==undefined) { A.b = {}; } eval('A.b.c = 1'); alert(A.b.c);
In this way, we dynamically create a composite object A. After understanding the principle, we can make some improvements to the form:
运单号:<input type="text" name="AwbPre" value="112" style="width:40px"/>-<input type="text" name="AwbNo" value="12312311"/><br/> 结算方式: <select name="SettlementMode" style="width:100px"> <option value="CASH" selected="selected">现金</option> <option value="MONTH">月结</option> </select> <br/> 不需要赋值的属性:<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("单号:" + AwbModel.AwbPre + "-" + AwbModel.AwbNo + "\n结算方式:" + AwbModel.SettlementMode + "\n不该有的属性:" + AwbModel.NotMe); </script>
In this way, as long as the name attribute of the form element is set correctly, when you need to collect form objects, you can quickly get a json object by calling the setFormModel function (of course this is just an example, only the first-level attribute is processed, if there are multiple level attribute, you can expand it yourself, it’s nothing more than doing some articles on strings)
I hope this article will be helpful to everyone in JavaScript programming.