Home >Web Front-end >JS Tutorial >JSONP implementation

JSONP implementation

高洛峰
高洛峰Original
2016-12-24 17:37:481216browse

Use jsonp to obtain data across domains.

js part

(function(window, document) {
    'use strict';
    var jsonp = function(url, data, callback) {
        //1、挂载回调函数
        var fnsuffix = Math.random().toString().replace('.', '');
        var cbFuncName = 'my_json_cb' + fnsuffix;
        window[cbFuncName] = callback;
        //2、将data转换成url字符串的形式
        //{id=1,count=4}==>id=1&count=4
        var querystring = url.indexOf('?') == -1 ? '?' : '&';     //判断url中最后是否有?,没有则为?
        for (var key in data) {
            querystring += key + '=' + data[key] + '&';
        }
        //3、处理url中回调函数 url+=callback=sdgade
        querystring += 'callback=' + cbFuncName;
        //querystring=?id=1&count=4&callback=sdgade
        //4、创建一个script标签
        var scriptElement = document.createElement('script');
        scriptElement.src = url + querystring;
        //5、把script标签放到页面上
        document.body.appendChild(scriptElement);
    };
    window.$jsonp = jsonp;
})(window, document)

Test

<!DOCTYPE html>
<html>
<head>
    <title>jsonp</title>
</head>
<body>
    <div id="htt"></div>
    <script type="text/javascript" src="http.js"></script>
    <script>
        (function(){
            $jsonp(&#39;http://api.douban.com/v2/movie/in_theaters&#39;,{},    
                function(data){
                    document.getElementById(&#39;htt&#39;).innerHTML=JSON.stringify(data);
                });
        })()
    </script>
</body>
</html>

in the page and the result can be returned. The page displays as, indicating that the acquisition is successful!

JSONP implementation


For more articles related to JSONP implementation, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn