Ajax的應用中,由於安全的問題,瀏覽器預設是不支援跨域調用的。傳統解決的方法,包括:(參考http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/)
Local proxy:Needs infrastructure (can't run a serverless client) and you getdouble-taxed on bandwidth and latency (remote - proxy - client).Flash:Remote host needs to deploy a crossdomain.xml file, Flash isrelatively proprietary and opaque to use, requires learning a one-offmoving target programming langage.Script tag:Difficult to know when the content is available, no standard methodology, can be considered a "security risk".
以上方法都各有缺陷,都不是很好多解決方案。後來出現了一種叫JSON with Padding的技術,簡稱 JSONP.(原理參考http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/),應用JSONP可以實現JSON資料的跨域調用。非常的幸運,JQuery1.2以後支援JSONP的應用。下面側重說明在JQuery中,Json的跨域調用。
應用JSONP實現Json資料跨域調用,需要伺服器端與用戶端的合作完成。引用Jquery官方的例子,用戶端掉用如下:
$.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("#images");if (i == 3)return false;});});
注意這裡調用的地址中jsoncallback=?是關鍵的所在!其中,符號會被Query自動替換成其他的回調方法的名稱,具體過程和原理我們這裡不理會。我們關心的是jsoncallback=?起什麼作用了?原來jsoncallback=?被替換後,會把方法名稱傳給伺服器。我們在伺服器端要做什麼工作呢?伺服器要接受參數jsoncallback,然後把jsoncallback的值作為JSON資料方法名稱返回,比如伺服器是JSP,我們會這樣做:
... String jsoncallback=request.getParameter("jsoncallback"); ... out.print(jsoncallback+"({\"account\":\"XX\",\"passed\":\"true\",\"error\":\"null\"})");
Jquery取得的資料可能如下:
JQUET0988788({"account":"XX","passed":"true","error":"null"})
總結,用JSONP要做兩件事:
1. 請求地址加參數:jsoncallback=?
2. 伺服器段把jsoncallback的值作為方法名傳回來,如JQUET098788(...)
博文來源:http://www.javaeye.com/topic/260647