javascript - 了解这段代码中的回调函数
问题描述
我在其他网站上看到了这段代码,但我不明白具体的 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>
解决方案
在您发布的代码中,有一个函数loadDoc
将另一个函数作为第二个参数 callback cFunction
。
loadDoc
,顾名思义,使用 ajax从 Internet 加载由url参数标识的文档。加载文档时,作为参数传递的 cFunction函数被称为传递当前XMLHttpRequest的引用。
loadDoc 所做的所有事情都是在用户单击按钮时完成的,必须加载的文档是ajax_info.txt,回调函数是myFunction
当使用包含响应的XMLHttpRequest对象作为参数下载文档时, loadDocmyFunction
会调用so ,因此 myFunction 可以读取响应并将其打印到 HTML 元素上。
在现代浏览器中,您可以使用JavaScript 调试工具,例如 console.log 和debugger
语句
推荐阅读
- python - PySpark 不同的列数
- elasticsearch - Boost certain keywords in search query
- c# - How to get filename from url considering all cases?
- python - Send a file to an external api from "InMemoryUploadedFile" in Django
- flutter - 缺少 state.build 的具体实现
- c - Fgets not working properly and something unusual happens with it
- java - DB2 外部存储过程(JAVA)
- node.js - localstack Aws cloudwatch 日志
- javascript - 如何将字符串转换为数字数组到字符串数组
- c++ - 对于仅具有矢量元素的类的 c'tor d'tor,默认值是否足够?