javascript - 在 AJAX/JavaScript 中,如何引用 undefined variable (匿名函数)?

标签 javascript ajax

我正在关注 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/

相关文章:

javascript - 无法从 Promise 中检索数据

javascript - 让一些路由由 Groovy 处理,另一些由 React-router v4 处理

ajax - 暴露 session 的 CSRF 保护 token 安全吗?

javascript - 为什么控制台不能定义id?

php - 使用 Jquery 和 Ajax 从 PHP 调用特定函数

javascript - ajax - 将数据作为 json 发送到 php 服务器并接收响应

javascript - 使用 AngularJS 在书写页面中进行预览

javascript - 如何管理 react 中的已读和未读通知?

jquery - 修改 jQuery jsonp 回调函数?

javascript - 有没有办法附加到对象 URL 或以其他方式创建流作为 URL?