DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> jQuery入門知識 >> JQuery特效代碼 >> Jsonp 跨域的原理以及Jquery的解決方案
Jsonp 跨域的原理以及Jquery的解決方案
編輯:JQuery特效代碼     
如果要進行跨域請求,我們可以通過使用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
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved