Use of the Eval () function in JavaScript

Source: Internet
Author: User

The eval () function parses a string into JavaScript code execution.

var str = "alert (' Hello World ');"  ; alert (str); alert (' Hello World ');
eval (str); Hello World

The eval () function is commonly used to parse a JSON string into a JSON object.

var jsonstr = "{' name ': ' Bossliu ', ' age ': +}"; alert (jsonstr.name);  Undefinedvar jsonobject = eval ("(" +jsonstr+ ")"); alert (jsonobject.name); Bossliu

Note: Because the JSON object is enclosed in {}, it is treated as a block of statements in JavaScript, so it must be cast to an expression, so add () on both sides of the JSONSTR

JSON is often used in Ajax to transmit data, and because the returned data is a string, the eval () function is required to parse it.

Json.txt content is as follows:

{    "person": {        "name": "Bossliu",        "age": +}    }

<!Doctyp HTML><HTML><Head><MetaCharSet= "Utf-8"><Script>functionAjax () {varAjax= NewXMLHttpRequest (); Ajax.open ("GET","Json.txt",true);    Ajax.send (); Ajax.onreadystatechange= function () {        if(Ajax.readystate== 4) {            if(Ajax.status==  $ ||Ajax.status== 304) {                varresult=Ajax.responsetext; varObject=Eval ("("+result+")"); document.getElementsByTagName ("Div")[0].innerhtml=Object.person.name; }        }    }}</Script></Head><Body><Buttononclick= "Ajax ()">Point Me</Button><Div></Div></Body></HTML>

Use of the Eval () function in JavaScript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.