【笔记】JSONP学习笔记

前言

不通过AJAX发送异步请求,而是构造一个<script></script>标签,指定src属性,来发送请求

准备服务器

  • 准备服务器,执行callback()函数,并将需要传递的数据通过参数传递给callback()函数
app.js
1
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}`)
});
1
node app.js

构造script标签

index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 定义处理数据的`callback()`回调函数
function callback(data) {
console.log(data);
}

// 构造script标签
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");

完成

参考文献

哔哩哔哩——渡一前端公开大师课