加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

jsonp(跨域)-------可以运行的小实例!

发布时间:2020-12-16 18:52:45 所属栏目:百科 来源:网络整理
导读:!DOCTYPE htmlhtml lang="en"head meta charset="UTF-8" script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"/script/headbodydiv id="divCustomers"/divdiv id="divCustomers2"/divscript type="text/javascript" //通过jquery的get方法实现跨域
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
</head>
<body>
<div id="divCustomers"></div>
<div id="divCustomers2"></div>
<script type="text/javascript">

    //通过jquery的get方法实现跨域
    $.get('https://ipinfo.io',function() {},"jsonp").always(function(resp) {
        var countryCode = (resp && resp.country) ? resp.country : "";
        countryCode = countryCode.toLowerCase();
        $('#divCustomers').text(countryCode);
        localStorage.setItem('countryCode',countryCode);
    });

    //通过jquery的ajax方法实现跨域
    $.ajax({
        type: "get",dataType:'jsonp',url:'https://ipinfo.io',success:function(resp){
            var countryCode = (resp && resp.country) ? resp.country : "";
            countryCode = countryCode.toLowerCase();
            $('#divCustomers2').text(countryCode);
            localStorage.setItem('countryCode',countryCode);
        },});

    //通过原生javascript的封装的方法实现跨域
    function jsonp(setting)
    {
        setting.data = setting.data || {};
        setting.key = setting.key||'callback';
        setting.callback = setting.callback||function(){};
        setting.data[setting.key] = '__onGetData__';

        window.__onGetData__ = function(data) {
            setting.callback (data);
        }
        var script = document.createElement('script');
        var query = [];
        for(var key in setting.data)
        {
            query.push(key + '=' + encodeURIComponent(setting.data[key]));
        }
        script.src = setting.url + '?' + query.join('&');
        document.head.appendChild(script);
        document.head.removeChild(script);
    }

    jsonp({
        url: 'http://photo.sina.cn/aj/index',key: 'jsoncallback',data: { page: 1,cate: 'recommend' },callback: function(ret) {
            console.log(ret)
        }
    });
</script>
</body>
</html>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读