跨域說明
跨域指請求和服務的域不一致,瀏覽器和h5的ajax請求有影響,而對服務端之間的http請求沒有限制。
跨域是瀏覽器攔截了服務器端返回的相應,不是攔截了請求。
jsonp跨域請求處理
jsonp(json with padding) 是 json的一種"使用模式",可以讓網頁從別的域名(網站)那獲取資料,繞過同源策略(若地址里面的協議、域名和端口號均相同則屬于同源),即跨域讀取數據。
jsonp:利用script標簽可以跨域,讓服務器端返回可執行的javascript函數,參數為要回發的數據。可看做帶有回調函數的ajax請求。
js代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<script type= "text/javascript" > $(function(){ /* //簡寫形式,效果相同 $.getjson("http://app.example.com/base/json.do?sid=1494&busiid=101&jsonpcallback=?", function(data){ $("#showcontent").text("result:"+data.result) }); */ $.ajax({ type : "get" , async: false , url : "http:/xxx" , datatype : "jsonp" , //數據類型為jsonp jsonp: "jsonpcallback" , //服務端用于接收callback調用的function名的參數 jsonpcallback: "自定義回調函數名" success : function(data){ alert(data.info) }, error:function(){ alert( 'fail' ); } }); }); </script> |
java后端處理代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@responsebody @requestmapping (value = "/url" , produces= mediatype.application_json) public string test( httpservletrequest request, httpservletresponse response) throws exception{ string result = getresult(); response.setheader( "pragma" , "no-cache" ); response.setheader( "cache-control" , "private,no-cache,no-store,max-age=0" ); response.setdateheader( "expires" , 0 ); string str=request.getparameter( "jsonpcallback" ); if (str== null ||str.equals( "" )) { return result; } else { return str + "(" + result + ")" ; } } |
cors(協議跨域資源共享)(cross-origin resource sharing)
它允許瀏覽器向跨源服務器,發出xmlhttprequest請求,從而克服了ajax只能同源使用的限制 詳細介紹
- access-control-allow-origin:* 允許所有域名的腳本訪問該資源
- access-control-allow-methods:get,post,put,delete,options 運行什么方式訪問資源
- access-control-expose-headers:x-requested-with 暴露的信息
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/chenzd/p/9989682.html