使用getJSON解決jquery跨域問題

來源:互聯網
上載者:User

    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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.