JSONP跨域请求的示例分析

这篇文章主要介绍了JSONP跨域请求的示例分析,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获。下面让小编带着大家一起了解一下。

创新互联-专业网站定制、快速模板网站建设、高性价比西畴网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式西畴网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖西畴地区。费用合理售后完善,十载实体公司更值得信赖。

维基百科的解释:

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's origin. The aggregation of the site's scheme, port number and host name identifies as its origin.

我的理解是:

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数据,就实现了跨域请求啦。

感谢你能够认真阅读完这篇文章,希望小编分享JSONP跨域请求的示例分析内容对大家有帮助,同时也希望大家多多支持创新互联,关注创新互联行业资讯频道,遇到问题就找创新互联,详细的解决方法等着你来学习!

新闻标题:JSONP跨域请求的示例分析
网页链接:https://www.cdcxhl.com/article28/phdojp.html

成都网站建设公司_创新互联,为您提供品牌网站设计面包屑导航网站维护软件开发全网营销推广网站排名

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

网站托管运营