Vue 中封装 JSONP跨域请求

1.JSONP

JSONP 是 JSON with padding(填充式 JSON 或参数式 JSON)的简写。

JSONP实现跨域请求的原理简单的说,就是动态创建”script”标签,然后利用”script”的src 不受同源策略约束来跨域获取数据。

JSONP 由两部分组成:回调函数和数据。回调函数是当响应到来时应该在页面中调用的函数。回调函数的名字一般是在请求中指定的。而数据就是传入回调函数中的 JSON 数据。

  • 动态创建”script”标签,设置其src,回调函数在src中设置:
var script = document.createElement("script");
script.src = "https://api.douban.com/v2/book/search?q=javascript&count=1&callback=handleResponse";
document.body.insertBefore(script, document.body.firstChild);
  • 在页面中,返回的JSON作为参数传入回调函数中,我们通过回调函数来来操作数据:
function handleResponse(response){
    // 对response数据进行操作代码
}
  • Vue中plugin封装:
// 处理http的参数
import qs from 'qs';

var hybrid = {
    // 用于vue安装这个插件 这个方法的第一个参数是 Vue 构造器 , 第二个参数是一个可选的选项对象:
    install (Vue, options) {
        // 把当前的对象挂载到vue的全局
        Vue.prototype.$hybrid = this;
        Vue.prototype.$eventHub= Vue.prototype.$eventHub || new Vue({data:{'message':''}, template:'<div> {{message}} </ div>'});
        this.$eventHub = Vue.prototype.$eventHub;
        Vue.prototype.$myMethod = function (options) {  // 4. 添加实例方法,通过把它们添加到 Vue.prototype 上实现
            // 逻辑...
            console.log('我是实例上的一个方法' + options);
        }
    },
    crossHttp(baseUrl,param={}) {
        return new Promise ((resolve, reject) => {
            let script = document.createElement("script");
            let params = '?' + qs.stringify(param);
            script.src = baseUrl + params;
            document.body.insertBefore(script, document.body.firstChild);
            window.handleResponse = function (response) {
                // 对response数据进行操作代码
                console.log('jsonp 回掉成功' + JSON.stringify(response));
                if (response.returnCode == '000000') {
                    resolve(response);
                } else {
                    reject(response);
                }
            }
        })
    }

}
// window对象
window.Hybrid = hybrid;
// 导出
export default hybrid;
  • 使用
引入 xx
Vue.use(xx);

 this.$hybrid.crossHttp('http://xx/xx/xx/', {
                            phone: xx,
                            channel: xx,
                            mobiletime: xx,
                            jsonpCallback: 'handleResponse'
                        }).then(rep => {
                            console.log(rep + 'ok');
                        }, err => {
                            console.log(err);
                        }).catch(err => {
                            console.log(err);
                        });;

jsonp框架
jsonp 原理

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值