【问题标题】:why isn't my eval turning the json string into an object为什么我的 eval 不把 json 字符串变成一个对象
【发布时间】:2010-01-22 06:12:30
【问题描述】:

当我执行 eval 函数时,它不会将我的 json 响应变成一个对象,它只会破坏我的代码。我尝试使用prototype.js 和JSON2.js 解析无济于事,请解释一下我在这里做错了什么?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <title>Inventory Management</title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Untitled Document</title>
        <script src="call.js" type="text/javascript"></script>
        <script src="prototype.js" type="text/javascript"></script>
    </head>
    <body>
    <div>
            <p id="resp" >new</p>
        <script type="text/javascript">



    var xhr;
    var results=getPlants(xhr,results);
    var plants;


    function getPlants(xhr,results){
        try {
            xhr=new XMLHttpRequest();   
            }catch(microsoft){
            try{
                xhr=new ActiveXObject("Msxml2.XMLHTTP");                
                }catch(othermicrosoft){
                    try{
                xhr = new ActiveXObject("Microsoft.XMLHTTP");               
                    }catch(failed){
                        xhr=false;
                        alert("ajax not supported");
                    }
                }               
        }   
        xhr.onreadystatechange= function () {
        if(xhr.readyState==4 && xhr.status==200) {
        results = xhr.responseText;                     
        }    
}
    xhr.open("GET","db_interactions.php",true);     
    xhr.send(null);
    alert("sent");
 return results;

}

plants = eval('('+results+')');

document.write(typeof(plants));
        </script>

    </div>

    </body>
</html>

【问题讨论】:

    标签: javascript json


    【解决方案1】:

    您正在发出一个异步请求。这意味着即使数据尚未准备好,该函数也会返回。但是您的调用假定在调用 getPlants 时 JSON 响应已准备好。这显然使 results 未定义,因为您没有等待它。

    把你的

    plants = eval('('+results+')');
    document.write(typeof(plants));
    

    xhr.onreadystatechange函数里面让它工作,或者同步打开连接

    xhr.open("GET","db_interactions.php",false);
    

    顺便说一下,不要使用eval解析JSON,因为代码可能被恶意注入。请改用 JSON 解析器。

    【讨论】:

    • 响应来自受信任的来源,当我在 getPlants 定义之外打印结果时,它会返回正确的数据,我只想弄清楚我的使用方式有什么问题eval 函数,它不会正确反序列化数据,并序列化我使用 php_encode 的数据
    • 您不会知道“受信任的”来源是否在其他地方存在导致您 XSS 的漏洞。始终最小化攻击面。此外,JSON 解析器可能比 eval 更快(在我的 Safari 上,eval 解析 JSON 的时间比 JSON.parse 多 36%)。
    猜你喜欢
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多