006 - 使用jsonP解决跨域.

1、JSONP是一个非官方的协议,它允许在服务器端集成script tags返回至客户端,通过javascript callback的形式实现跨域访问。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        window.onload = function () {
            document.getElementById('btnOk').onclick = function () {
                //创建一对script标签
                var jsonp = document.createElement('script');
                //指定加载的域上的资源
                jsonp.src = 'http://www.bbb.com/index.php?fn=callback&_='+new Date().getTime();
                //将标签加入到head标签中
                document.getElementsByTagName('head')[0].appendChild(jsonp);
            }
        };

        //处理函数
        function callback( msg ) {
            alert(msg.name + ":" + msg.age);
        }
    </script>
</head>

<body>
    <input type="button" id="btnOk" value="确定">
</body>
</html>
<?php
    //生成数组数据
    $data = array(
        'name' => 'lisi',
         'age' => 20
    )

    //生成json字符串
    $str = json_encode( $data );

    //获取回调函数名称
    $fn = $_GET['fn'];

    //输出结果,执行客户端js函数
    echo $fn.'('.$str.')';


2、JQ解决跨域问题

支持 $.ajax() $.get() $.getJSON()
	/*JQ解决跨域问题*/
        $.ajax({
            type : 'get',
            url : 'http://www.bb.com/demo.php',
            dataType : 'jsonp',
            jsonp : 'fn',
            success : function (msg) {
                alert(msg.name + ':' + msg.age);
            }
        });

        $.get('http://www.bb.com/demo.php?fn=?',function (msg) {
            alert(msg.name);
        });

        $.getJSON('http://www.bb.com/demo.php?fn=?',function (msg) {
            alert(msg.name);
        });

<?php
    //生成数组数据
    $data = array(
        'name' => 'lisi',
         'age' => 20
    )

    //生成json字符串
    $str = json_encode( $data );

    //获取回调函数名称
    $fn = $_GET['fn'];

    //输出结果,执行客户端js函数
    echo $fn.'('.$str.')';

3、axios 解决跨域
// 继承
Vue.prototype.$http = axios;
 
// 实例化
var vm = new Vue({
    el: '#box',
    data: {
 
    },
    created: function () {
        // console.log(111);
        this.hello();
    },
    methods: {
        hello: function () {
            this.$http.get('http://localhost:3000/axios?cb=cb', {
                // withCredentials:true
            }).then(function (data, msg) {
                console.log(data);
                console.log(msg);
            }).
            catch (function (err) {
                console.log(err);
            })
        }
    }
})

参考链接:
JQ:   http://www.runoob.com/json/json-jsonp.html
axios:  http://cnodejs.org/topic/5930430f03dba3510d8a62c6




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值