为什么当我 eval() 来自 Ajax 调用的 responseText 出现 "undefined" 一词?

Why when I eval() the responseText from an Ajax call does the word "undefined" appear?

我有一个简单的测试如下所示。它工作正常,但由于某种原因 "undefined" 这个词出现在弹出窗口中。没有什么能让我理解未定义的东西。以前有人经历过吗?

HTML

<html><head>
<style>#popup{border:1px solid black;background:#eadcce;padding:10px;margin:35px;display:none;}</style>
<script>
function popup(){
    var z;
    if(window.XMLHttpRequest){z=new XMLHttpRequest();}else{z=new ActiveXObject("Microsoft.XMLHTTP");}
    z.onreadystatechange=function(){if(z.readyState==4&&z.status==200){
            if(z.responseText != ''){
                    document.getElementById('popup').innerHTML=eval(z.responseText);
                    document.getElementById('popup').style.display="block";
            }
    }}
    z.open("POST",'/test2.php');z.send();
}
</script></head><body>
Push the button to open the popup: <button onclick="parent.popup();">Open Popup</button>
<div id="popup"></div>
</body></html>

test2.php

console.log("test");

一切正常,除了单词 "undefined" 出现在我的弹出窗口中。有谁知道为什么?我正在使用 Firefox 55.0.3。

eval 计算 JavaScript 代码,return 计算最后一个语句的结果。函数 console.log returns undefined, 所以 eval('console.log("test")') also returnsundefined(after printing the stringtest` 到浏览器的日志)。

如果您不希望您的对话框包含 undefined,请不要将求值 JavaScript 字符串中的最后一个语句作为对 return 的函数的调用undefined。例如,字符串

console.log("test"); "foobar";
当使用 eval 计算时,

将 return 字符串 foobar,因为这是最后一条语句的值。

同样,字符串

console.log("test"); ['a', 'b'].indexOf('a');

将在计算时 return 0,因为这是最终语句中 indexOf 调用的 returned 值。