跨域问题-jsonp

前端之家收集整理的这篇文章主要介绍了跨域问题-jsonp前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

前端
同源策略并不会拦截静态资源请求,那么就将接口伪装成资源,然后后端配合返回一个前端预定义的方法调用,将返回值放入调用函数的形参即可

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <title>Title</title>
    <script>
        //前端预定义
        function getName(rep){
            document.write(rep.name)
            console.log(rep)
        }
    </script>
</head>
<body>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script src="http://localhost:8082?callback=getName"></script>
</body>
</html>

 

后端
后端以node为例,其他语言大同小异

var http = require("http");
const url = require("url");
http.createServer(function (request,response) {
    let params = url.parse(request.url,true);
    response.end(params.query.callback + `(${JSON.stringify({name:"abc"})})`);
}).listen(8082);

 

效果

分享图片



分享图片



分享图片

 

补充
当然了,如果你觉得麻烦,你可以用jq的jsonp或者其他封装ajax支持jsonp的插件效果一样

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script>
        let url=http://localhost:8082?callback=getName;
        $.ajax({
            url: url,type: "get",dataType: "jsonp",jsonpCallback: "getName",success: function (rep) {
                document.write(rep.name)
                console.log(rep)

            }
        })
    </script>
</head>
<body></body>
</html>

猜你在找的Json相关文章