js 跨域访问 找了好长时间

一直没时间玩js,看到douban网的开放api后,查了些文档,了解了一下 jsonp 跨域请求方式.跟大家分享一下。

 

其实 jsonp 是个很简单的一个东西。

主要是利用了 <script/> 标签对 javascript 文档的动态解析来实现。(其实也可以用eval函数)

 

来个超简单的例子:

首先是准备客户端的代码,

 

Html代码 复制代码
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml" >  
  3. <head>  
  4.     <title>Test Jsonp</title>  
  5.     <script type="text/javascript">  
  6.             function jsonpCallback(result)   
  7.             {   
  8.             alert(result.msg);   
  9.             }   
  10.         </script>  
  11.     <script type="text/javascript" src="http://crossdomain.com/jsonServerResponse?jsonp=jsonpCallback"></script>  
  12. </head>  
  13. <body>  
  14. </body>  
  15. </html>   
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Test Jsonp</title>
	<script type="text/javascript">
        	function jsonpCallback(result)
        	{
			alert(result.msg);
        	}
    	</script>
	<script type="text/javascript" src="http://crossdomain.com/jsonServerResponse?jsonp=jsonpCallback"></script>
</head>
<body>
</body>
</html> 

 

其中 jsonCallback 是客户端注册的,获取跨域服务器上的json数据后,回调的函数。

http://crossdomain.com/jsonServerResponse?jsonp=jsonpCallback

这个 url 是跨域服务器取 json 数据的接口,参数为回调函数的名字,返回的格式为

 

Js代码 复制代码
  1. jsonpCallback({msg:'this is json data'})  
jsonpCallback({msg:'this is json data'})

 

Jsonp原理:

首先在客户端注册一个callback, 然后把callback的名字传给服务器。

 

此时,服务器先生成 json 数据。 

然后以 javascript 语法的方式,生成一个function , function 名字就是传递上来的参数 jsonp.

 

最后将 json 数据直接以入参的方式,放置到 function 中,这样就生成了一段 js 语法的文档,返回给客户端。

 

客户端浏览器,解析script标签,并执行返回的 javascript 文档,此时数据作为参数,传入到了客户端预先定义好的 callback 函数里.(动态执行回调函数)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值