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