jsonp跨域原理解析

來源:互聯網
上載者:User

標籤:blog   http   io   os   java   ar   strong   檔案   資料   

前言: 跨域請求是前台開發中經常遇到的情境,但是由於瀏覽器同源策略,導致A域下普通的http請求沒法載入B域下的資料,跨域問題由此產生。但是通過script標籤的方式卻可以載入非同域下的js,因此可以利用這一特性,進行跨域資料請求。

先看一下跨域導致的問題,測試域分別為 localhost 和 www.icity366.com, 下文分別對應A域和B域,測試檔案為A域下的 data.jsp, 我們在A(localhost)域下請求B(www.icity366.com)域下的資料,看一下data.jsp中關鍵代碼:

    $.ajax({url : "http://www.icity366.com:8080/addresslist/test/Data.do?method=getData",data : {callback : "getData"},//dataType : "json",type : "get",success : function(data){alert(data);},error : function(XmlHttpRequest,textStatus,errorThrown){//debugger;alert(textStatus);}  })

 結果為alert("error"),瀏覽器提示跨域:

  

利用script標籤解決跨域

在data.jsp頁面中定義好回調方法,

function getData(data){  alert(data.name);}

通過script標籤引用js:

<script type="text/javascript" src="http://www.icity366.com:8080/addresslist/test/Data.do?method=getData&callback=getData"></script>

伺服器端java代碼如下:

String callback = request.getParameter("callback");Map<String,String> data = new HashMap<String,String>();data.put("name", "Liyx");data.put("age", "25");String dataJson = JsonUtils.convertToString(data);//Map->jsonresponse.getWriter().write(callback+"("+dataJson+")");

 請求結果:

  java端返回  getData({"age":"25","name":"Liyx"}),頁面執行getData(),彈出 Liyx, 說明<script>標籤可跨域獲得資料。

 

 JSONP方式跨域寫法

  json核心就是:允許使用者傳遞一個callback參數給服務端,然後服務端返回資料時會將這個callback參數作為函數名來包裹住JSON資料,這樣用戶端就可以隨意定製自己的函數來自動處理返回資料了。先看一下寫法:

var url = "http://www.icity366.com:8080/addresslist/test/Data.do?method=getData&callback=?";$.getJSON(url,function(data){alert(data.name);  //Liyx})

  callback=? 先傳遞?過去,jquery會自動產生一個全域函數來替換callback=?中的問號,看一下java端的輸出,

jQuery171004718876606784761_1411549835461({"age":"25","name":"Liyx"}),長串即為產生的全域函數,該function會自動銷毀,並把資料傳遞到回調方法中。

 

jsonp跨域原理解析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.