您现在的位置是:首页 > 学无止境 > web前端web前端

vue-resource通过jsonp实现跨域请求数据

管理员2020-03-30 14:03:48web前端2469人已围观

简介vue-resource通过jsonp实现跨域请求数据

由于没有准备服务器环境,下面就通过js模拟jsonp实现跨域请求数据。

假如在www.a.com的前端页面index.html写如下的代码,创建一个子组件,里面的data有一个owlist空数组,这个数据想通过jsonp获取来自别的域名(如:www.b.com/jsonp.js)下的数据

var myListA = {
	template: `
		<ul>
			<li v-for="item in owlist"><a :title="item.name" :href="item.url" target="_blank"><i class="fa" :class="rnd_fa()"></i> {{item.name}}</a></li>
		</ul>
	`,
	data: function () {
		return {
			"owlist":[],
			fa_icons:["fa-internet-explorer","fa-share-alt","fa-apple","fa-chrome","fa-edge"]

		}
	},
	methods:{
		rnd_fa: function () {
			var _index = Math.floor((Math.random()*(this.fa_icons.length))); 
			return this.fa_icons[_index];
		},
		getOlist: function(){
		    this.$http.jsonp('https://andy168.gitee.io/api/data/jsonp.js',{jsonpCallback:"getData"}).
		    then(function (res) {
		    	console.log(res);
		    	this.owlist = res.data.s;
		        
		    },function () {
		    	console.log("fair");

		    });

		}
	},
	created: function(){
		this.getOlist()
	}
}

jsonp.js的代码如下:

getData({
	a:"22",
	s:[
		{
			"id":"6",
			"name": "世博园专题",
			"url": "http://www.ffepcn.com/m/index.html"
		},
		{
			"id":"5",
			"name": "文件管理",
			"url": "http://www.ffepcn.com/Public/ActivityProject/kod/"
		},
		{
			"id":"4",
			"name": "商户在线查询",
			"url": "http://www.ffepcn.com/m/others/datatable/index3.html"
		},
		{
			"id":"3",
			"name": "商户权限管理",
			"url": "http://www.ffepcn.com/m/others/merchant/index.php"
		},
		{
			"id":"2",
			"name": "zaker报名数据",
			"url": "http://www.ffepcn.com/m/others/zaker/list.php"
		},
		{
			"id":"1",
			"name": "名家居世博园",
			"url": "http://www.ffepcn.com"
		}
	]
});

这样当我们访问www.a.com/index.html时就可以获取到数据 了,这里由于没有使用服务器端的语言,所以只好拿js文件做了一个简单的例子,实际上,在服务器端下php环境下可以通过$_GET['callback']这样去获取的。

最后看下控制台返回的结果

vue-resource通过jsonp实现跨域请求数据

小郭博客

标签云 更多

站长特荐

关闭
QQ 微信 支付宝扫一扫打赏