posts - 83,  comments - 2,  views - 35295

jsonp(JSON with Padding)是一种使用模式,可以实现跨域获取数据,原理是基于由于script标签不受限于同源策略,script标签可以通过src属性请求到其他服务器上的数据

浏览器同源策略:在当前网页中,若想到发送一个请求,请求url必须满足 协议,域名,端口 三者相同,才能得到正常响应,否则属于跨域请求,浏览器会限制跨域请求。

jsonp是实现跨域一种的方式。

一、服务器端代码实现

复制代码
let express = require('express');
var http = require('http');
let port = 1013;

let app = new express();
app.get('/say', function (req, res) {
  let { cb } = req.query;

  res.write(`${cb}('hello,jsonp')`);
  res.end();
});
app.listen(port, () => {
  try {
    console.log(`http server start listening at http://localhost:${port}`);
  } catch (error) {}
});
复制代码

 

二、客户端代码1

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
</head>

<body></body>

</html>
<script>
    function sayHello(data) {
        alert(data)
    }
</script>

<script type="text/javascript" src="http://localhost:1013/say?cb=sayHello"></script>

 

三、客户端代码2

使用自定义jsonp函数,效果同上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
</head>
 
<body></body>
 
</html>
<script>
    const callback = 'sayHello'
    function jsonp(p) {
        let { url, params, cb } = p;
        return new Promise((resolve, reject) => {
            let script = document.createElement('script');
            //定义回调函数,服务器返回sayHello()执行时调用
            window[cb] = function (data) {
                resolve(data);
                document.body.removeChild(script)
            };
            params = { ...params, cb };
            let arrs = [];
            for (const key in params) {
                arrs.push(`${key}=${params[key]}`);
            }
 
            script['src'] = `${url}?${arrs.join('&')}`;
            document.body.appendChild(script)
        });
    }
    jsonp({
        url: 'http://localhost:1013/say',
        params: { wd: 'jsonp' },
        cb: callback,
    }).then((data) => {
        //callback
        console.log(data)
    });
 
</script>

  

posted on   码农-编程小子  阅读(170)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示