Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Javascript happens to use the eval function to assemble the method by which the form input is a jason object


May 08, 2021 JSON


Table of contents


When web development in the ajax way, you often encounter a scenario where you collect form inputs, form a jason object, and then post the object directly to the service side before saving it.


It is common practice to write code in js that looks like this:

var myObj = {};
myObj.x = document.getElementById("x").value;
myObj.y = document.getElementById("y").value;
//... 
//然后ajax post或get提交

This is fine when there are not many form elements, but it can be too laborious to write this code if a form has dozens or more inputs.

Fortunately, javascript has an evil eval function that can help us with some work like 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, which, once we understand the principles, can make some improvements to the form:

Bill of Lading No.:

<input type="text" name="AwbPre" value="112" style="width:40px"/>-<input type="text" name="AwbNo"  value="12312311"/><br/>

How to settle:

<select name="SettlementMode" style="width:100px">
    <option value="CASH" selected="selected">现金</option>
    <option value="MONTH">月结</option>
</select>
<br/>

Properties that do not require an assignment:

<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 form element's name property is set correctly, when you need to collect form objects, call the setFormModel function, you can quickly get a jason object (of course, this is only an example, only deal with the case of first-level properties, if there are multi-level properties, we go to extend it, nothing more than to do some articles on the string)

The role of the Eval() function in JavaScript

Let's start with the simplest understanding
eval can execute string generation statements, similar to SQL's exec().
What is the use of eval? S ometimes we don't know what statements to execute in advance, and we don't know what statements to execute until the conditions and parameters are given, and that's when eval comes in use. For example:
Let's do a fusion(), the function is to enter the name of the two objects in the web page, and then the program will join the values of the two objects together to output.

 function output(a,b) 
    { 
      var tmpa,tmpb; 
      tmpa=document.all.a.value; 
      tmpb=document.all.b.value; 
      document.write(tmpa+tmpb); 
    } 
  output('input1','input2');

This way you'll be prompted for errors such as "document.all.a is not an object" and "document..b not an object." O riginally javascript a and b as object names, how can javascript a value as an object name? That's when you're going to use eval and change the code to this:

function output(a,b) 
  { 
    var tmpa,tmpb; 
    tmpa=eval("document.all."+a+".value"); 
    tmpb=eval("document.all."+b+".value"); 
    document.write(tmpa+tmpb); 
  } 
 output('input1','input2'); 

Javascript then takes out the values of a, b, and then runs in combination with the previous document.all. and the later .value, so that the values of input1 and input2 can be successfully removed.

Read the basic understanding above what eval means
Then look at the understanding below
Slightly advanced, using the example of replacing pictures in the DOM

Use of the Eval function in Javascript?

eval() function

JavaScript has a number of tips to make programming easier.

One of them is the eval() function, which can execute a string as if it were a JavaScript expression.

To give a small example:

 var the_unevaled_answer = "2 + 3";
 var the_evaled_answer = eval("2 + 3");
 alert("the un-evaled answer is " + the_unevaled_answer + " and the 
 evaled answer is " + the_evaled_answer);

If you run this eval program, you'll see that the string "2 plus 3" in JavaScript is actually executed.

So when you set the_evaled_answer value of the value of the data set to eval ("2 plus 3"), JavaScript will understand and return the 2 and 3 the_evaled_answer.

This may seem silly, but it can actually do interesting things. With eval, for example, you can create functions directly based on the user's input.

This allows the program to change the program itself depending on the time or user input, and you can get amazing results by citing one example and three.

In practice, eval is rarely used, but you may have seen someone use eval to get objects that are difficult to index.

One of the problems with the document object model (DOM) is that sometimes it's painful to get the object you're asking for.

For example, here's a function that asks the user which image to transform: Transform which image you can use the following function:

function swapOne()
   {
      var the_image = prompt("change parrot or cheese","");
      var the_image_object;
         if (the_image == "parrot")
            {
               the_image_object = window.document.parrot;
            } 
        else 
            {
               the_image_object = window.document.cheese;
            }
            the_image_object.src = "ant.gif";
            }
        连同这些image标记:
     [img src="/stuff3a/parrot.gif" name="parrot"]
     [img src="/stuff3a/cheese.gif" name="cheese"]

Notice a few lines of statements like this:

the_image_object = window.document.parrot;

It applied an image object to a variable. Strange as it may seem, it has no problem with grammar.

But what if you have 100 images instead of two? You have to write a bunch of if-then-else statements, if only it could be like this:

function swapTwo()
    {
       var the_image = prompt("change parrot or cheese","");
       window.document.the_image.src = "ant.gif";
    }

Unfortunately, JavaScript will look for an image called the_image instead of the "cheese" or "parrot" you want, so you get the error message: "I haven't heard of an object the_image".

Fortunately, eval can help you get what you want.

function simpleSwap()
    {
        var the_image = prompt("change parrot or cheese","");
         var the_image_name = "window.document." + the_image;
        var the_image_object = eval(the_image_name);
       the_image_object.src = "ant.gif";
    }

If the user fills in the "parrot" in the prompt box, a string is created in the second line, window.document.parrot.

Then the third line containing eval means: "Give me the object window.document.parrot" - that's the image object you want. O nce you have acquired this image object, you can set its src property to .gif. A little scared? D on't. It's actually quite useful, and people use it a lot.

We often get to the Eval function in the middle of Javascript, which some people find strange and powerful enough to turn some strings.
When we need to convert a normal string into a concrete object, this function eval function is used to evaluate a string as a numeric expression, with the syntax:

eval(expr)

Here expr is a string argument that is valued. I f the string is an expression, eval values the expression, and if the argument represents one or more JavaScript statements, eval executes those statements. T he eval function can be used to convert a date from a format (always a string) to a numeric expression or number.

==============================

The Eval function

Features: Explain javascript code first, and then execute it


Usage: Eval (codeString)


CodeString is a string that contains Javascript statements and is compiled after eval using the Javascript engine.


Comments:


Examples: eval (id , "_icon.src" / imgs / collapse_up.gif');


id is a previously set parameter, while strings in double quotes need to be compiled


Reference:


--------------------------------------------------------------------------------

function tophide(id)     //id indicates menu
{
     if (top.topframeset.rows == "31,*")
     {
         top.topframeset.rows = "86,*";
         eval(id + "_icon.src="/imgs/collapse_up.gif'");
         eval(id + "_icon.alt='Collapse The Head'");
         head.style.display = "block"
         }
     else
     {
         top.topframeset.rows = "31,*";
         eval(id + "_icon.src="/imgs/collapse_down.gif'");
         eval(id + "_icon.alt='Expand The Head'");
         head.style.display = "none"
     }
}

If you still don't understand the eval function in javascript in depth


Found for this article to start a suitable title is not so easy, ha ha, so in this first explain the following two purposes of this article:
(1) Introduces the use of the eval function in javascript
(2) How to execute global code within a function

First of all, the use of eval, the content is relatively simple, familiar can be skipped.

The use of eval
The eval function receives an argument s, which returns s directly if s is not a string. O therwise, the s statement is executed. If the result of the s statement execution is a value, this value is returned, otherwise the underfined is returned.
It is important to note that the object declaration syntax " does not return a value and needs to be bracketed to return a value, as in a simple example:

var code1='"a" + 2';    //表达式
var code2='{a:2}';      //语句
alert(eval(code1));     //->'a2'
alert(eval(code2));     //->undefined
alert(eval('(' + code2 + ')'));    //->[object Object]

As you can see, for object declaration statements, simply execution does not return a value. I n order to return an object declaration statement such as the commonly used " T his is also one of the basic principles of using JSON for Ajax development. As you can clearly see in the example, the second alt statement outputs underfined, while the third bracketed output is the object represented by the statement.
&#9658; N ow let's focus on how to execute global code within a function. To illustrate this problem, let's look at an example:

var s='global';    //定义一个全局变量
function demo1(){
    eval('var s="local"');
}
demo1();
alert(s);    //->global

It is well understood that the demo1 function above is equivalent to: function demo1() , which defines a local variable s.
So the final output is global is not a strange thing, after all, we can clearly distinguish between local and global variables.
On closer inspection, you can see the characteristics of the eval function, which is always executed within the context variable space (also known as a package, closure) where it is called, whether it is a variable definition or a function definition, so the following code produces errors that are not defined by the function:

var s='function test(){return 1;}';     //一个函数定义语句
function demo2(){
    eval(s);
}
demo2();
alert(test());    //->error:test is not defined

This is because the test function is defined in local space, which is accessible within the demo2 function and not accessible outside.

In real-world Ajax development, sometimes we need to dynamically get code from the server to execute to mitigate the problem of overloading code at once, or some code is generated through Javascript itself, hoping to execute it with the eval function.

But such dynamic acquisition of code is typically done within functions, such as:

function loadCode(){
    var code=getCode();
    eval(code);
}

It can be seen that eval can not be executed in the global space, which brings a lot of problems to development, but also saw a lot of people depressed about this.
But now even finally found a solution, hey hey, can be compatible with IE and Firefox at the same time, the method is as follows:

var X2={}    //my namespace:)
X2.Eval=function(code){
if(!!(window.attachEvent && !window.opera)){
  //ie
  execScript(code);
}else{
  //not ie
  window.eval(code);
}
}

Now if you want to define global code within a function, you can call the X2.Eval (code) method, for example:

var s='global';
function demo3(){
X2.Eval('var s="local"');
}
demo3();
alert(s); //->'local'

As you can see, the global variable s"local" has been redefined within the demo3 function.
It is important to note that X2.Eval does not return a value, if you want to evaluate the expression, or use the system's eval function. X 2. Eval is designed for global code definition only.
In fact, see here, perhaps some people feel that the problem is too easy to solve the point, ha ha, but found that this method needs some luck and skill:
(1) For Internet Explorer, the default has provided such a function: execScript, used to execute code in global space, but not many people know.
(2) For Firefox browsers, calling the eval function directly is performed in the caller's space, and in global space if window.eval is called. T he number of people who know is estimated to be even lower. After all, allert (eval.window.eval) returns true!

Firefox's eval function is indeed strange, but its source can also be found in the javascript specification:

If value of the eval property is used in any way other than a direct 
call (that is, other than by the explicit use of its
name as an Identifier which is the MemberExpression in a 
CallExpression), or if the eval property is assigned to,
an EvalError exception may be thrown.

This presumably means that the execution of the eval function is related to the caller, but does not address the issue of its execution context. So IE and Firefox are hard to say, you know the solution is good.