作家
登录

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

作者: 来源:www.28hudong.com 2013-03-30 00:50:30 阅读 我要评论

如果要进行跨域请求,我们可以通过使用html的script标记来进行跨域请求,并在响应中返回要执行的script代码,其中可以直接使用JSON传递javascript对象。这种跨域的通讯方式称为JSONP。 个人理解: 就是在客户端动态注册一个函数function a(data),然后将函数名传到服务器,服务器返回一个a({/*json*/})到客户端运行,这样就调用客户端的function a(data),从而实现了跨域. 复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W//DTD XHTML Transitional//EN" "http://www.worg/TR/xhtmlDTD/xhtmltransitional.dtd"> <html xmlns="http://www.worg/xhtml" > <head> <title>Test Jsonp</title> <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script> <script type="text/javascript"> function jsonpCallback(result) { $.each(result.items, function(i,item){ $("<img/>").attr("src", item.media.m).appendTo("body"); if ( i == 3 ) return false; }); } </script> </head> <body> <script type="text/javascript" src="http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=jsonpCallback"></script> </body> </html> jQuery的解决方案: 复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W//DTD XHTML Transitional//EN" "http://www.worg/TR/xhtmlDTD/xhtmltransitional.dtd"> <html xmlns="http://www.worg/xhtml" > <head> <title>Test Jsonp</title> <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data) { $.each(data.items, function(i, item) { $("<img/>").attr("src", item.media.m).appendTo("body"); if (i == 3) return false; }); }); }); </script> </head> <body></body> </html> jquery 的jsoncallback是动态生成的,真正请求服务器的地址:http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=jsonp1274058545738

  推荐阅读

  基于jquery的回到页面顶部按钮

css代码: 复制代码 代码如下: .scroll-up { background: #dcdcdc url('up.png') no-repeat center center; width:48px !important; /*for ff and other standard browser*/ height:48px !important; _width: 58px>>>详细阅读


本文标题:Jsonp 跨域的原理以及Jquery的解决方案

地址:http://www.17bianji.com/kaifa2/JS/24474.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)