简体   繁体   English

javascript函数调用返回未定义且页面持续加载

[英]javascript function call returns undefined and page continouly loads

I have a HTML code as follows 我有一个HTML代码如下

<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="loadDoc()">ALERT DATA</button>
<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function() 
  {
    if (xhttp.readyState == 4 && xhttp.status == 200) 
    {    
           eval(xhttp.responseText);   
        }
  };
 xhttp.open("GET", "sample1.js", true)
 xhttp.send();
}
</script>
</body>
</html>

Using the AJAX call I am able to call a javascript alert func 使用AJAX调用,我可以调用javascript警报函数

function callMe(){
 alert("DATA IS 5");
}
document.write(callMe());

When I am running this simple HTML file on firefox it gives me "undefined" on the browser. 当我在firefox上运行此简单的HTML文件时,它在浏览器上给我“未定义”的信息。 I dont really understand why.I returned "" from the function callMe() so that removed the "undefined" on the browser but the page seems to be keep on loading . 我真的不明白为什么。我从函数callMe()返回了“”,以便删除了浏览器中的“未定义”,但页面似乎仍在继续加载。 Is there anything I am doing wrong ? 我做错了什么吗?

Your method callMe() evaluates to undefined (since it doesn't return anything and alert(...) -being the last command- will evaluate to undefined). 您的方法callMe()的评估结果为undefined(因为它不返回任何内容,并且alert(...)-作为最后一条命令-的评估结果为undefined)。

Therefore you will be writing "undefined" to your document. 因此,您将在文档中写入“未定义”。

Thanks for your support . 谢谢你的支持 。

I re wrote the js code as follows 我重新编写了js代码,如下所示

function callMe(){
 alert("DATA IS 5");
return " ";
}
document.write(callMe());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM