javascript - 为什么我的 eval 没有将 json 字符串转换为对象

标签 javascript json

当我执行 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>

最佳答案

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

把你的

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

xhr.onreadystatechange函数内使其工作,或以同步方式打开连接

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

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

关于javascript - 为什么我的 eval 没有将 json 字符串转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2115413/

相关文章:

我可以从传感器读取值,然后将其添加到 RF24l01 网络的 JSON 字符串中吗

javascript - 在完整的浏览器窗口中显示图像,但仅在图像太大时才按比例缩小

javascript - 如何检测脚本是在浏览器中还是在 Node.js 中运行?

javascript - 通过@Input()传递的数据

javascript - 如何在 Store 中使用 Vue 插件?

java - 在 Java Android 中解码 JSON

javascript - Nouislider slider 在 react 中不起作用

android - 未调用 Moshi 自定义适配器

json - 如何获取嵌套在 NSDictionary 字典中的值?

javascript - JSON.parse javascript 字符串