eval()函數可以將字符串解析為javascript代碼執行。
var str = "alert('hello world');"; alert(str); //alert('hello world');
eval(str); //hello world
eval()函數常用於將json字符串解析為json對象。
var jsonStr = "{'name':'bossLiu','age':27}"; alert(jsonStr.name); //undefined var jsonObject = eval("("+jsonStr+")"); alert(jsonObject.name); //bossLiu
注意:由於json對象是用{}括起來的,在javascript中會被當成語句塊處理,所以必須將其強制轉換成表達式,所以在jsonStr的兩邊要加上()
在ajax中常常使用json作為傳輸數據,由於返回的數據是字符串,所以需要使用eval()函數解析。
json.txt內容如下:
{ "person": { "name": "bossLiu", "age": 27 } }
<!DOCTYP html> <html> <head> <meta charset="utf-8"> <script> function ajax() { var ajax = new XMLHttpRequest(); ajax.open("GET","json.txt",true); ajax.send(); ajax.onreadystatechange = function () { if (ajax.readyState == 4) { if (ajax.status == 200 || ajax.status == 304) { var result = ajax.responseText; var object = eval("("+result+")"); document.getElementsByTagName("div")[0].innerHTML = object.person.name; } } } } </script> </head> <body> <button onclick="ajax()">點我</button> <div></div> </body> </html>