网页跨域之jsonp的使用,包含jquery和js实现

来源:互联网 发布:电脑电视直播软件排名 编辑:程序博客网 时间:2024/05/16 02:38
这里就不讲原理了,原理可以参考链接:
http://justcoding.iteye.com/blog/1366102

这篇文章写得非常好,非常有参考价值.

jsonp相比其他跨域方法(其他跨域方法有;window.name,iframe,webSocket等),应该是最好用的,也是用的最多的吧.

直接贴源代码了:这里用的是百度提供的搜索接口:https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=web前端

其中wd为搜索的关键字,回调函数的接受参数名是cb

<!DOCTYPE html><html><head><title>测试jsonp</title><meta charset="utf-8"><script type="text/javascript" src="https://cdn.bootcss.com/jquery/2.2.2/jquery.js"></script><script type="text/javascript">/*jquery  jsonp请求*/$(function(){$.ajax({type:'get',url:'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=web前端',dataType:'jsonp',jsonp:'cb',//根据服务器参数设置的,百度提供的是cbsuccess:function(data){var content=document.querySelector('[content]');var keyword=document.createElement('h3');keyword.innerHTML="关键字为:"+data.q;content.appendChild(keyword);var ul=document.createElement('ul');data.s.forEach(function(item,index,array){var li=document.createElement('li');li.innerHTML=item;ul.appendChild(li);});content.appendChild(ul);}});});/*原生js jsonp请求*/function cbSuccess(data){console.log(data);}window.onload=function(){var script=document.createElement('script');script.type="text/javascript";script.src='https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=web前端&cb=cbSuccess';//cbSuccess为回调函数var content=document.querySelector('[content]');content.appendChild(script);}/*通过对比发现明显原生js更容易实现jsonp,也更容易理解原理*/</script></head><body>        <div content></div></body></html>
代码均实践过,可以直接拷贝到本地,查看效果.
阅读全文
1 0
原创粉丝点击