Vue.js AJAX 跨域调用 JSONP | jQuery | vue-resource | axios

44 篇文章 0 订阅
10 篇文章 0 订阅

Vue.js AJAX 跨域调用 JSONP

预览地址:http://djk8888.byethost32.com/VueAjaxJsonP/index.html

jQuery:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Vue + jQuery AJAX</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>

<body>
    <div id="app">
        <table border="1">
            <tr>
                <th>编号</th>
                <th>姓名</th>
            </tr>
            <tr v-for="people in peoples">
                <td>{{people.id}}</td>
                <td>{{people.name}}</td>
            </tr>
        </table>
    </div>

</body>

</html>
<script>
    var vv = new Vue({
        el: "#app",
        data: {
            peoples: [],
        },
        created: function () {
            this.bind();
        },
        methods: {
            bind: function () {
                $.ajax({
                    type: "get",
                    dataType: "jsonp",
                    jsonp: "callback",
                    jsonpCallback:"callback",
                    url: "http://djk8888.byethost32.com/VueAjax/jsonp.html",
                    success: function (data) {
                        $.each(data, function (index, item) {
                            var sth = { id: item.id, name: item.name };
                            vv.peoples.push(sth);
                        });
                    }
                });
            },
        }
    });
</script>

预览地址:http://djk8888.byethost32.com/VueAjaxJsonP/jQuery.html

vue-resource:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Vue.js Ajax(vue-resource)</title>
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>
</head>

<body>
    <div id="app">
        <table border="1">
            <tr>
                <th>编号</th>
                <th>姓名</th>
            </tr>
            <tr v-for="people in peoples">
                <td>{{people.id}}</td>
                <td>{{people.name}}</td>
            </tr>
        </table>
    </div>
    <script>
        var vv = new Vue({
            el: "#app",
            data: {
                peoples: [],
            },
            created: function () {
                this.bind();
            },
            methods: {
                bind: function () {
                    this.$http.jsonp('http://djk8888.byethost32.com/VueAjax/jsonp.html', { jsonpCallback: "callback" }).then(function (res) {
                        for (var index in res.data) {
                            var sth = { id: res.data[index].id, name: res.data[index].name };
                            vv.peoples.push(sth);
                        }
                    }, function () {
                        console.log('请求失败处理');
                    });
                },
            }
        });
    </script>

</body>

</html>

预览地址:http://djk8888.byethost32.com/VueAjaxJsonP/resource.html

axios(axios本身不支持调用jsonp,通过原生javascript的ajax来调用jsonp,当然也可以用jQuery来调用)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Vue.js Ajax(axios)</title>
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
</head>

<body>
    <div id="app">
        <table border="1">
            <tr>
                <th>编号</th>
                <th>姓名</th>
            </tr>
            <tr v-for="people in peoples">
                <td>{{people.id}}</td>
                <td>{{people.name}}</td>
            </tr>
        </table>
    </div>
    <script>
        var vv = new Vue({
            el: "#app",
            data: {
                peoples: [],
            },
            created: function () {
                this.bind();
            },
            methods: {
                bind: function () {
                    js_ajax({
                        url: "http://djk8888.byethost32.com/VueAjax/jsonp.html",  // 请求地址
                        jsonp: "callback", // 采用jsonp请求,且回调函数名为"jsonpCallbak",可以设置为合法的字符串    
                        data: {},  // 传输数据
                        success: function (data) {  // 请求成功的回调函数         
                            for (var index in data) {
                                var sth = { id: data[index].id, name: data[index].name };
                                vv.peoples.push(sth);
                            }
                        },
                        error: function (error) { }  // 请求失败的回调函数
                    });
                },
            },
        });
        //原生javascript的ajax调用jsonp
        function js_ajax(params) {
            params = params || {};
            params.data = params.data || {};
            var json = params.jsonp ? jsonp(params) : json(params);
            // jsonp请求  
            function jsonp(params) {
                //创建script标签并加入到页面中  
                var callbackName = params.jsonp || params.jsonpCallback;
                var head = document.getElementsByTagName('head')[0];
                // 设置传递给后台的回调参数名  
                params.data['callback'] = callbackName;
                var data = formatParams(params.data);
                var script = document.createElement('script');
                head.appendChild(script);
                //创建jsonp回调函数  
                window[callbackName] = function (json) {
                    head.removeChild(script);
                    clearTimeout(script.timer);
                    window[callbackName] = null;
                    params.success && params.success(json);
                };
                //发送请求  
                script.src = params.url + '?' + data;
                //为了得知此次请求是否成功,设置超时处理  
                if (params.time) {
                    script.timer = setTimeout(function () {
                        window[callbackName] = null;
                        head.removeChild(script);
                        params.error && params.error({
                            message: '超时'
                        });
                    }, time);
                }
            };
            //格式化参数  
            function formatParams(data) {
                var arr = [];
                for (var name in data) {
                    arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
                };
                // 添加一个随机数,防止缓存  
                arr.push('v=' + random());
                return arr.join('&');
            }
            // 获取随机数  
            function random() {
                return Math.floor(Math.random() * 10000 + 500);
            }
        }
    </script>
</body>

</html>

预览地址:http://djk8888.byethost32.com/VueAjaxJsonP/axios.html

 

相关文章:

Vue.js Ajax(jQuery) | Vue.js Ajax(vue-resource) | Vue.js Ajax(axios) https://blog.csdn.net/djk8888/article/details/106012045 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1、一个众所周知的问题,Ajax直接请求普通文件存在无权限访问的问题,甭管你是静态页面、动态网页、web服务、WCF,只要是请求,一律不准;   2、不过我们又发现,Web页面上调用js文件时则不受是否的影响(不仅如此,我们还发现凡是拥有”src”这个属性的标签都拥有的能力,比如[removed]、、<iframe>);   3、于是可以判断,当前阶段如果想通过纯web端(ActiveX控件、服务端代理、属于未来的HTML5之Websocket等方式不算)访问数据就只有一种可能,那就是在远程服务器上设法把数据装进js格式的文件里,供客户端调用和进一步处理;   4、恰巧我们已经知道有一种叫做JSON的纯字符数据格式可以简洁的描述复杂数据,更妙的是JSON还被js原生支持,所以在客户端几乎可以随心所欲的处理这种格式的数据;   5、这样子解决方案就呼之欲出了,web客户端通过与调用脚本一模一样的方式,来调用服务器上动态生成的js格式文件(一般以JSON为后缀),显而易见,服务器之所以要动态生成JSON文件,目的就在于把客户端需要的数据装入进去。   6、客户端在对JSON文件调用成功之后,也就获得了自己所需的数据,剩下的就是按照自己需求进行处理和展现了,这种获取远程数据的方式看起来非常像AJAX,但其实并不一样。   7、为了便于客户端使用数据,逐渐形成了一种非正式传输协议,人们把它称作JSONP,该协议的一个要点就是允许用户传递一个callback参数给服务端,然后服务端返回数据时会将这个callback参数作为函数名来包裹住JSON数据,这样客户端就可以随意定制自己的函数来自动处理返回数据了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值