我正在关注 AJAX 上的 W3Schools 教程,它提供了一个使用 JavaScript 回调函数的示例 here (代码粘贴在下面):
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
{
loadXMLDoc("ajax_info.txt",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction()">Change Content</button>
</body>
</html>
让我感到困惑的是,这如何将 onreadystatechange
设置为在触发时运行 cfunc
,但未定义 cfunc
。我所有(公认的基本)编程经验都表明这应该会导致错误,因为您不能引用变量/函数/等。在定义它(或传递它)之前。
This answer另一个 StackOverflow 问题说 cfunc
是在另一个函数中定义的“匿名函数”,但这只会让我更加困惑......我是否误解了这里的一些基本知识?
最佳答案
cfunc
在这一行被赋值:
function loadXMLDoc(url,cfunc)
调用 cfunc
时传递一个函数:
loadXMLDoc("ajax_info.txt",function() /* and the next several lines */
"anonymous function" defined within another function, but that only confused me more… Am I misunderstanding something fundamental here?
函数只是一种对象。您可以像传递数组、对象、数字和其他任何内容一样传递它们。
关于javascript - 在 AJAX/JavaScript 中,如何引用 undefined variable (匿名函数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8949305/