使用jsonp向非同源服务器端发送请求数据
jsonp 代码优化
1.客户端需要将函数名称传递到服务器端
2.将script 请求的发送变成动态请求
案例:
02.使用jsonp向同源服务器端请求数据(1).html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
function fn (data) {
console.log('客户端的fn函数被调用了')
console.log(data);
}
</script>
<!-- 1.将非同源服务器端的请求地址写在script标签的src属性中 -->
<script src="http://localhost:3001/test"></script>
</body>
</html>
03.使用jsonp向非同源服务器端请求数据(2).html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
function fn2 (data) {
console.log('客户端的fn函数被调用了')
console.log(data);
}
</script>
<!-- 1.将非同源服务器端的请求地址写在script标签的src属性中 -->
<script src="http://localhost:3001/better?callback=fn2"></script>
</body>
</html>
03.使用jsonp向非同源服务器端发送请求数据(3).html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button id="btn">点我发送请求</button>
<script>
function fn2 (data) {
console.log('客户端的fn函数被调用了')
console.log(data);
}
</script>
<script type="text/javascript">
// 获取按钮
var btn = document.getElementById('btn');
// 为按钮添加点击事件
btn.onclick = function () {
// 创建script标签
var script = document.createElement('script');
// 设置src属性
script.src = 'http://localhost:3001/better?callback=fn2';
// 将script标签追加到页面中
document.body.appendChild(script);
// 为script标签添加onload事件
script.onload = function () {
// 将body中的script标签删除掉
document.body.removeChild(script);
}
}
</script>
</body>
</html>
app.js定义:
app.get('/better',(req,res) => {
//接收客户端传递过来的函数的名称
const fnName = req.query.callback;
//将函数名称对应的函数调用代码返回给客户端
res.send(result);
});