Jsonp 跨域的原理以及Jquery的解决方案

前端之家收集整理的这篇文章主要介绍了Jsonp 跨域的原理以及Jquery的解决方案前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

转自:http://www.cnblogs.com/DanielChow/archive/2010/05/17/1737070.html

原理:JSONP即JSON with Padding。由于同源策略的限制,XmlHttpRequest只允许请求当前源(域名、协议、端口)的资源。如果要进行跨域请求,我们可以通过使用html的script标记来进行跨域请求,并在响应中返回要执行的script代码,其中可以直接使用JSON传递javascript对象。这种跨域的通讯方式称为JSONP。

个人理解:

就是在客户端动态注册一个函数function a(data),然后将函数名传到服务器,服务器返回一个a({/*json*/})到客户端运行,这样就调用客户端的function a(data),从而实现了跨域.

<! DOCTYPEhtmlPUBLIC " -//W//DTDXHTMLTransitional//EN " " http://www.worg/TR/xhtmlDTD/xhtmltransitional.dtd " > @H_301_36@ < htmlxmlns = " http://www.worg/xhtml " > @H_301_36@ < head > @H_301_36@ < title > TestJsonp < / title> @H_301_36@ < scriptsrc = " http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js " type = " text/javascript " >< / script> @H_301_36@ < scripttype = " text/javascript " > @H_301_36@ function jsonpCallback (result)@H_301_36@{@H_301_36@$.each(result.items, function (i,item){@H_301_36@$( " <img/> " ).attr( " src " ,item.media.m).appendTo( " body " );@H_301_36@ if (i == 3 ) return false ;@H_301_36@});@H_301_36@}@H_301_36@ < / script> @H_301_36@ < / head> @H_301_36@ < body > @H_301_36@ < scripttype = " text/javascript " src = " http://api.flickr.com/services/Feeds/photos_public.gne?tags=cat&tagmode=any&format=json& jsoncallback=jsonpCallback " >< / script> @H_301_36@ < / body> @H_301_36@ < / html>

jQuery的解决方案:

<! DOCTYPEhtmlPUBLIC " -//W//DTDXHTMLTransitional//EN " " http://www.worg/TR/xhtmlDTD/xhtmltransitional.dtd " > @H_301_36@ < htmlxmlns = " http://www.worg/xhtml " > @H_301_36@ < head > @H_301_36@ < title > TestJsonp < / title> @H_301_36@ < scriptsrc = " http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js " type = " text/javascript " >< / script> @H_301_36@ < scripttype = " text/javascript " > @H_301_36@$( function (){@H_301_36@ $.getJSON( " http://api.flickr.com/services/Feeds/photos_public.gne?tags=cat&tagmode=any&format=json& jsoncallback=? " , function (data){@H_301_36@$.each(data.items,item.media.m).appendTo( " body " );@H_301_36@ if (i == 3 ) return false ;@H_301_36@});@H_301_36@});@H_301_36@});@H_301_36@ < / script> @H_301_36@ < / head> @H_301_36@ < body >< / body> @H_301_36@ < / html>

jquery 的jsoncallback是动态生成的,真正请求服务器的地址:http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=jsonp1274058545738

猜你在找的Json相关文章