1. 程式人生 > >請求跨域

請求跨域

參考自:https://www.cnblogs.com/dowinning/archive/2012/04/19/json-jsonp-jquery.html  (寫的很好)

跨域的情況

跨域就是跨域名,跨埠,跨協議

直接在ajax中發起跨域的請求是獲取不到相應的內容的

 

訪問不了的案例(java)

1.在本地搭建兩個tomcat埠不同的專案,我這裡是8099和8098埠

2.編寫controller以供測試

	@RequestMapping(value="/list", produces ="application/text;charset=utf-8")
	@ResponseBody
	public String list(){
		return "我是8098埠返回的資料";
	}

3.在頁面中通過ajax發起跨域和不跨域的請求進行對比

不跨域:

	
<a class="test1" href="#">我是測試跨域的(請求http://localhost:8098/list)  不跨域</a><br>
	
$(function(){
		$(".test1").click(function(){
			$.get('http://localhost:8098/list',function(data){
				$(".p1").text(data);
			});
		});
	});
	

可以得到結果:

跨域

<a class="test2" href="#">我是測試跨域的(請求http://localhost:8099/list)  跨域</a><br>

	$(function(){
		$(".test2").click(function(){
			$.get('http://localhost:8099/list',function(data){
				$(".p2").text(data);
			});
		});
	});
	

是獲取不到資料的,出現了跨域

 

Jsonp跨域請求

簡單實現:

在遠端編寫remote.js檔案,本地跨域去訪問

localHandler({"result":"我是遠端js帶來的資料"});

本地只需要寫出來資源的位置就可以跨域訪問:

<script type="text/javascript" src="http://localhost:8099/js/remote.js"></script>

資料的顯示:

remote.js檔案,修改為資料

localHandler({"result":"我是遠端js帶來的資料"});

本地呼叫

    <script type="text/javascript">
    var localHandler = function(data){
        alert('我是本地函式,可以被跨域的remote.js檔案呼叫,遠端js帶來的資料是:' + data.result);
    };
    </script>
    <script type="text/javascript" src="http://localhost:8099/js/remote.js"></script>

 

Jquery實現Jsonp跨域請求(複製的)

後臺的資料:

flightHandler({
    "code": "CA1998",
    "price": 1780,
    "tickets": 5
});

跨域呼叫

<script type="text/javascript" src=jquery.min.js"></script>
      <script type="text/javascript">
     jQuery(document).ready(function(){ 
        $.ajax({
             type: "get",
             async: false,
             url: "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998",
             dataType: "jsonp",
             jsonp: "callback",//傳遞給請求處理程式或頁面的,用以獲得jsonp回撥函式名的引數名(一般預設為:callback)
             jsonpCallback:"flightHandler",//自定義的jsonp回撥函式名稱,預設為jQuery自動生成的隨機函式名,也可以寫"?",jQuery會自動為你處理資料
             success: function(json){
                 alert('您查詢到航班資訊:票價: ' + json.price + ' 元,餘票: ' + json.tickets + ' 張。');
             },
             error: function(){
                 alert('fail');
             }
         });
     });
     </script>