首页 > 解决方案 > 了解这段代码中的回调函数

问题描述

我在其他网站上看到了这段代码,但我不明白具体的 cFunction 和 url

function loadDoc(url, cFunction) {
  var xhttp;
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      cFunction(this);
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}

function myFunction(xhttp) {
  document.getElementById("demo").innerHTML =
    xhttp.responseText;
}
<div id="demo">

  <h2>The XMLHttpRequest Object</h2>

  <button type="button" onclick="loadDoc('ajax_info.txt', myFunction)">Change Content</button>
</div>

标签: javascriptajaxcallback

解决方案


在您发布的代码中,有一个函数loadDoc将另一个函数作为第二个参数 callback cFunction

loadDoc,顾名思义,使用 ajax从 Internet 加载由url参数标识的文档。加载文档时,作为参数传递的 cFunction函数被称为传递当前XMLHttpRequest的引用。

loadDoc 所做的所有事情都是在用户单击按钮时完成的,必须加载的文档是ajax_info.txt,回调函数是myFunction

当使用包含响应的XMLHttpRequest对象作为参数下载文档时, loadDocmyFunction会调用so ,因此 myFunction 可以读取响应并将其打印到 HTML 元素上。

在现代浏览器中,您可以使用JavaScript 调试工具,例如 console.log 和debugger语句


推荐阅读