首页 > web前端 > js教程 > 正文

JSONP跨域请求的理解(代码示例)

不言
发布: 2018-11-26 14:36:36
转载
2683人浏览过

本篇文章给大家带来的内容是关于jsonp跨域请求的理解(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

对于JSONP一直是知半解,今天利用周末整理了一下

维基百科的解释:

JSONP (JSON with Padding or JSON-P[1]) is a javascript pattern to request data by loading a <script> tag. It was proposed by Bob Ippolito in 2005.[2] JSONP enables sharing of data bypassing same-origin policy. The policy disallows running JavaScript to read media DOM elements or XHR data fetched from outside the page&#39;s origin. The aggregation of the site&#39;s scheme, port number and host name identifies as its origin.</script>

我的理解是:

1、前端编写自己的函数,用script标签发送get请求把函数名字带上
2、服务器端接送到请求后获取前端发送请求时的query,添加上自己的数据返回后。
3.、前端获取返回的内容其实就自己的函数调用实参是数据对象。

  • 解释的有点懵逼没关系,用栗子说话。

前端代码

<!doctype html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
<script>
    //编写调用函数
    function getremotedata(data) {
        console.log(data);
    }
</script>
<!--用script标签get方法把数据请求发送到后端-->
<script src="http://localhost:3999/?callback=getremotedata"></script>
</body>
</html>
登录后复制

后端代码

//用node编写一个简单的服务器
const http = require('http');
const urlModule = require('url');
const server = http.createServer();
server.on('request', function (req, res) {
    //urlModule.parse(req.url.url)的请求 就是这个对象
    // {
    //   protocol: null,
    //   slashes: null,
    //   auth: null,
    //   host: null,
    //   port: null,
    //   hostname: null,
    //   hash: null,
    //   search: '?callback=getremotedata',
    //   query: 'callback=getremotedata',
    //   pathname: '/',
    //   path: '/?callback=getremotedata',
    //   href: '/?callback=getremotedata' }
    // 对象结构赋值得到query是一个对象
    const {pathname: url, query} = urlModule.parse(req.url, true)
    if (url === '/') {
        var data = {
            name: '大毛',
            age: 18,
            gender: '未知'
        };
        // 解析query的请求得到前端发送的函数名称,加上括号调用此函数,函数里加实参servedata返回
        var scripteStr = `${query.callback}(${JSON.stringify(data)})`
        console.log(scripteStr)
        res.end(scripteStr)
    } else {
        res.end('404')
    }
});
server.listen('3999', function () {
    console.log('server is running 3999')
})
登录后复制

这样前端发送请求,无论回调是什么,后端都会返回回调加data数据,就实现了跨域请求啦。

第一写感觉有点语言不清,大家把代码自己敲一遍就懂了

自学前端3个月,想找一个基础的前端工作

以上就是JSONP跨域请求的理解(代码示例)的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:segmentfault网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号