前言
不通过AJAX发送异步请求,而是构造一个<script></script>标签,指定src属性,来发送请求
准备服务器
- 准备服务器,执行
callback()函数,并将需要传递的数据通过参数传递给callback()函数
app.js1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| const http = require("http");
const port = 8080;
const app = http.createServer();
app.on("/list", function (req, resp) { resp.end(` callback(["data1", "data2"]) `); });
app.listen(port, function () { console.log(`http://127.0.0.1:${port}`) });
|
构造script标签
index.js1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function callback(data) { console.log(data); }
function doRequest(url) { const script = document.createElement("script"); script.src = url; script.onload = function () { script.remove(); } document.body.appendChild(script); }
doRequest("http://127.0.0.1:8080/list");
|
完成
参考文献
哔哩哔哩——渡一前端公开大师课