jsonp通过动态创建script标签的方式来实现跨域通信。原理是浏览器允许html标签在不同的域名下加载资源。
<script> var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'XX.com?value1=1&value2=2'; document.head.appendChild(script);
// 回调函数
function callBack(res){
alert(JSON.stringify(res));
}
</script>
// jquery实现 $.ajax({ url: 'XX.com', type: 'get', dataType: 'jsonp', // 请求方式为jsonp jsonpCallback: "onBack", // 自定义回调函数名 data: {} });
// vue.js 实现 this.$http.jsonp('XX.com', { params: {}, jsonp: 'onBack' }).then((res) => { console.log(res); })