JSONP实现跨域

1. 原理:

利用HTML中script标签可以加载其他域下的js

2. JSONP方法思路:

  1. 首先利用script标签请求数据。如下:
<script src="http://api.jirengu.com/weather.php"></script>

问题出现了,请求的数据是JSON格式的数据

  1. 后端解析callback这个参数获取字符串showData,在发送数据时做如下处理
<script src="http://api.jirengu.com/weather.php?callback=showData"></script>

之前后端回复的数据是 {"city": "hangzhou", "weather": "晴天"} ,而现在是showData({"city": "hangzhou", "weather": "晴天"})

  1. 前端为什么收到这个showData({"city": "hangzhou", "weather": "晴天"})数据可以当js来执行,因为提前定义了一个shouData的全局函数,然后在函数内部处理参数即可
<script>
function showData(ret){
console.log(ret);
}
</script>
<script src="http://api.jirengu.com/weather.php?callback=showData"></script>

3. JSONP是什么

JSONP是通过 script 标签加载数据的方式去获取数据当做 JS 代码来执行 提前在页面上声明一个函数,函数名通过接口传参的方式传给后台,后台解析到函数名后在原始数据上「包裹」这个函数名,发送给前端。换句话说,JSONP 需要对应接口的后端的配合才能实现。

4. 代码例子:

服务器代码

var http = require('http')
var fs = require('fs')
var path = require('path')
var url = require('url')

http.createServer(function (req, res) {
    var pathObj = url.parse(req.url, true)
    switch (pathObj.pathname) {
        case '/getNews':
            var news = [
                "第11日前瞻:中国冲击4金 博尔特再战200米羽球",
                "正直播柴飚/洪炜出战 男双力争会师决赛",
                "女排将死磕巴西!郎平安排男陪练模仿对方核心"
            ]
            res.setHeader('content-type', 'text/json;charset=utf-8')
            if (pathObj.query.callback) {
                res.end(pathObj.query.callback + '(' + JSON.stringify(news) + ')')

            } else {
                res.end(JSON.stringify(news))
            }
            break
        default:
            fs.readFile(path.join(__dirname,pathObj.pathname),function (e,data) {
                if(e){
                    res.writeHead(404,'Not Found')
                    res.end('<h1>404 Not Found</h1>')
                }
                else {
                    res.end(data)
                }
            })
    }
}).listen(8080)

html代码

<!DOCTYPE html>
<html>
<body>
<div class="container">
    <ul class="news">
    </ul>
    <button class="show">show news</button>
</div>

<script>


    $('.show').addEventListener('click', function () {
        var script = document.createElement('script');
        script.src = 'http://127.0.0.1:8080/getNews?callback=appendHtml';
        document.head.appendChild(script);
        document.head.removeChild(script);
    })

    function appendHtml(news) {
        var html = '';
        for (var i = 0; i < news.length; i++) {
            html += '<li>' + news[i] + '</li>';
        }
        console.log(html);
        $('.news').innerHTML = html;
    }

    function $(id) {
        return document.querySelector(id);
    }


</script>
</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容