原生js和vue-jsonp实现jsonp跨域实现使用必应每日壁纸

原生js实现jsonp跨域

注意jsonp跨域需要后台支持。

实现效果

这里是用的必应每日壁纸api
在这里插入图片描述
代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <button onclick="pre()" >上一张</button>
  <button onclick="next()" >下一张</button>
  <img id="img"  src="" alt="">
<script>
  let a = 0
  create(a);
  function pre(){
    a = a + 1;
    create(a)
  }
  function next(){
    if(a === 0){
      return false;
    }else{
      a = a - 1;
      create(a)
    }
  }

  function create(d){
    let script = document.createElement('script');
    script.id = 'getBiyingJsonp'
    script.src = `https://bing.ioliu.cn/v1/?d=${d}&w=1920&h=1080&callback=callback`
    document.body.insertBefore(script, document.body.firstChild);
  }
  
  function callback(e){
    document.getElementById('img').src = e.data.url;
    // 移除用于跨域的script
    document.getElementById('getBiyingJsonp').remove();
  }
</script>
</body>
</html>

vue中用 vue-jsonp实现跨域

注意:你可能对this.$jsonp有些疑惑,因为没有看到他在哪里赋值给vue的原型,vue-jsonp内部已经实现了绑到原型的操作了。

<template>
	<div>
		<img :src="src" alt="">
	</div>
</template>

<script>
//如果你在很多地方要用到jsonp可以把它放到main.js中
	import Vue from 'vue'
	import vueJsonp from 'vue-jsonp'
	Vue.use(vueJsonp)
	export default {
		data() {
			return {
				src:''
			}
		},
		created(){
			this.getImg(0)
		},
		methods: {
			getImg(d) {
				let url = `https://bing.ioliu.cn/v1/`;
				 this.$jsonp(url,{
					params:{
						d:d,
						w:1920,
						h:1080
					}
				}).then(res=>{
					console.log(res)
					this.src = res.data.url;
				}).catch(err=>{
					console.log(err)
				})
			}
		},
	}
</script>
发布了96 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_35958891/article/details/103903968