標籤: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跨域原理解析