跨域的安全限制都是對瀏覽器端來說的,服務(wù)器端是不存在跨域安全限制的。 瀏覽器的同源策略限制從一個源加載的文檔或腳本與來自另一個源的資源進行交互。 如果協(xié)議,端口和主機對于兩個頁面是相同的,則兩個頁面具有相同的源,否則就是不同源的。 如果要在js里發(fā)起跨域請求,則要進行一些特殊處理了?;蛘撸憧梢园颜埱蟀l(fā)到自己的服務(wù)端,再通過后臺代碼發(fā)起請求,再將數(shù)據(jù)返回前端。
這里講下使用jquery的jsonp如何發(fā)起跨域請求及其原理。
先看下準備環(huán)境:兩個端口不一樣,構(gòu)成跨域請求的條件。 獲取數(shù)據(jù):獲取數(shù)據(jù)的端口為9090 請求數(shù)據(jù):請求數(shù)據(jù)的端口為8080
1、先看下直接發(fā)起ajax請求會怎么樣 下面是發(fā)起請求端的代碼: 1 <%@ page pageEncoding="utf-8" contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>跨域測試</title> 5 <script src="js/jquery-1.7.2.js"></script> 6 <script> 7 $(document).ready(function () { 8 9 $("#btn").click(function () { 10 $.ajax({ 11 url: 'http://localhost:9090/student', 12 type: 'GET', 13 success: function (data) { 14 $(text).val(data); 15 } 16 }); 17 18 }); 19 20 }); 21 </script> 22 </head> 23 <body> 24 <input id="btn" type="button" value="跨域獲取數(shù)據(jù)" /> 25 <textarea id="text" style="width: 400px; height: 100px;"></textarea> 26 </body> 27 </html> 請求的結(jié)果如下圖:可以看到跨域請求因為瀏覽器的同源策略被攔截了。
2、接下來看如何發(fā)起跨域請求。解決跨域請求的方式有很多,這里只說一下jquery的jsop方式及其原理。 首先我們需要明白,在頁面上直接發(fā)起一個跨域的ajax請求是不可以的,但是,在頁面上引入不同域上的js腳本卻是可以的,就像你可以在自己的頁面上使用<img src=""> 標(biāo)簽來隨意顯示某個域上的圖片一樣。 比如我在8080端口的頁面上請求一個9090端口的圖片:可以看到直接通過src跨域請求是可以的。
3、那么看下如何使用<script src="">來完成一個跨域請求: 當(dāng)點擊"跨域獲取數(shù)據(jù)"的按鈕時,添加一個<script>標(biāo)簽,用于發(fā)起跨域請求;注意看請求地址后面帶了一個callback=showData的參數(shù); showData即是回調(diào)函數(shù)名稱,傳到后臺,用于包裹數(shù)據(jù)。數(shù)據(jù)返回到前端后,就是showData(result)的形式,因為是script腳本,所以自動調(diào)用showData函數(shù),而result就是showData的參數(shù)。 至此,我們算是跨域把數(shù)據(jù)請求回來了,但是比較麻煩,需要自己寫腳本發(fā)起請求,然后寫個回調(diào)函數(shù)處理數(shù)據(jù),不是很方便。 1 <%@ page pageEncoding="utf-8" contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>跨域測試</title> 5 <script src="js/jquery-1.7.2.js"></script> 6 <script> 7 //回調(diào)函數(shù) 8 function showData (result) { 9 var data = JSON.stringify(result); //json對象轉(zhuǎn)成字符串 10 $("#text").val(data); 11 } 12 13 $(document).ready(function () { 14 15 $("#btn").click(function () { 16 //向頭部輸入一個腳本,該腳本發(fā)起一個跨域請求 17 $("head").append("<script src='http://localhost:9090/student?callback=showData'><\/script>"); 18 }); 19 20 }); 21 </script> 22 </head> 23 <body> 24 <input id="btn" type="button" value="跨域獲取數(shù)據(jù)" /> 25 <textarea id="text" style="width: 400px; height: 100px;"></textarea> 26 27 </body> 28 </html> 服務(wù)端: 1 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 2 response.setCharacterEncoding("UTF-8"); 3 response.setContentType("text/html;charset=UTF-8"); 4 5 //數(shù)據(jù) 6 List<Student> studentList = getStudentList(); 7 8 9 JSONArray jsonArray = JSONArray.fromObject(studentList); 10 String result = jsonArray.toString(); 11 12 //前端傳過來的回調(diào)函數(shù)名稱 13 String callback = request.getParameter("callback"); 14 //用回調(diào)函數(shù)名稱包裹返回數(shù)據(jù),這樣,返回數(shù)據(jù)就作為回調(diào)函數(shù)的參數(shù)傳回去了 15 result = callback + "(" + result + ")"; 16 17 response.getWriter().write(result); 18 } 結(jié)果:
4、再來看jquery的jsonp方式跨域請求: 服務(wù)端代碼不變,js代碼如下:最簡單的方式,只需配置一個dataType:'jsonp',就可以發(fā)起一個跨域請求。jsonp指定服務(wù)器返回的數(shù)據(jù)類型為jsonp格式,可以看發(fā)起的請求路徑,自動帶了一個callback=xxx,xxx是jquery隨機生成的一個回調(diào)函數(shù)名稱。 這里的success就跟上面的showData一樣,如果有success函數(shù)則默認success()作為回調(diào)函數(shù)。 1 <%@ page pageEncoding="utf-8" contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>跨域測試</title> 5 <script src="js/jquery-1.7.2.js"></script> 6 <script> 7 8 $(document).ready(function () { 9 10 $("#btn").click(function () { 11 12 $.ajax({ 13 url: "http://localhost:9090/student", 14 type: "GET", 15 dataType: "jsonp", //指定服務(wù)器返回的數(shù)據(jù)類型 16 success: function (data) { 17 var result = JSON.stringify(data); //json對象轉(zhuǎn)成字符串 18 $("#text").val(result); 19 } 20 }); 21 22 }); 23 24 }); 25 </script> 26 </head> 27 <body> 28 <input id="btn" type="button" value="跨域獲取數(shù)據(jù)" /> 29 <textarea id="text" style="width: 400px; height: 100px;"></textarea> 30 31 </body> 32 </html> 效果:
再看看如何指定特定的回調(diào)函數(shù):第30行代碼 回調(diào)函數(shù)你可以寫到<script>下(默認屬于window對象),或者指明寫到window對象里,看jquery源碼,可以看到j(luò)sonp調(diào)用回調(diào)函數(shù)時,是調(diào)用的window.callback。 然后看調(diào)用結(jié)果,發(fā)現(xiàn),請求時帶的參數(shù)是:callback=showData;調(diào)用回調(diào)函數(shù)的時候,先調(diào)用了指定的showData,然后再調(diào)用了success。所以,success是返回成功后必定會調(diào)用的函數(shù),就看你怎么寫了。 1 <%@ page pageEncoding="utf-8" contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>跨域測試</title> 5 <script src="js/jquery-1.7.2.js"></script> 6 <script> 7 8 function showData (data) { 9 console.info("調(diào)用showData"); 10 11 var result = JSON.stringify(data); 12 $("#text").val(result); 13 } 14 15 $(document).ready(function () { 16 17 // window.showData = function (data) { 18 // console.info("調(diào)用showData"); 19 // 20 // var result = JSON.stringify(data); 21 // $("#text").val(result); 22 // } 23 24 $("#btn").click(function () { 25 26 $.ajax({ 27 url: "http://localhost:9090/student", 28 type: "GET", 29 dataType: "jsonp", //指定服務(wù)器返回的數(shù)據(jù)類型 30 jsonpCallback: "showData", //指定回調(diào)函數(shù)名稱 31 success: function (data) { 32 console.info("調(diào)用success"); 33 } 34 }); 35 }); 36 37 }); 38 </script> 39 </head> 40 <body> 41 <input id="btn" type="button" value="跨域獲取數(shù)據(jù)" /> 42 <textarea id="text" style="width: 400px; height: 100px;"></textarea> 43 44 </body> 45 </html> 效果圖:
再看看如何改變callback這個名稱:第23行代碼 指定callback這個名稱后,后臺也需要跟著更改。 1 <%@ page pageEncoding="utf-8" contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>跨域測試</title> 5 <script src="js/jquery-1.7.2.js"></script> 6 <script> 7 8 function showData (data) { 9 console.info("調(diào)用showData"); 10 11 var result = JSON.stringify(data); 12 $("#text").val(result); 13 } 14 15 $(document).ready(function () { 16 17 $("#btn").click(function () { 18 19 $.ajax({ 20 url: "http://localhost:9090/student", 21 type: "GET", 22 dataType: "jsonp", //指定服務(wù)器返回的數(shù)據(jù)類型 23 jsonp: "theFunction", //指定參數(shù)名稱 24 jsonpCallback: "showData", //指定回調(diào)函數(shù)名稱 25 success: function (data) { 26 console.info("調(diào)用success"); 27 } 28 }); 29 }); 30 31 }); 32 </script> 33 </head> 34 <body> 35 <input id="btn" type="button" value="跨域獲取數(shù)據(jù)" /> 36 <textarea id="text" style="width: 400px; height: 100px;"></textarea> 37 38 </body> 39 </html> 后臺代碼: 1 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 2 response.setCharacterEncoding("UTF-8"); 3 response.setContentType("text/html;charset=UTF-8"); 4 5 //數(shù)據(jù) 6 List<Student> studentList = getStudentList(); 7 8 9 JSONArray jsonArray = JSONArray.fromObject(studentList); 10 String result = jsonArray.toString(); 11 12 //前端傳過來的回調(diào)函數(shù)名稱 13 String callback = request.getParameter("theFunction"); 14 //用回調(diào)函數(shù)名稱包裹返回數(shù)據(jù),這樣,返回數(shù)據(jù)就作為回調(diào)函數(shù)的參數(shù)傳回去了 15 result = callback + "(" + result + ")"; 16 17 response.getWriter().write(result); 18 } 效果圖:
最后看看jsonp是否支持POST方式:ajax請求指定POST方式 可以看到,jsonp方式不支持POST方式跨域請求,就算指定成POST方式,會自動轉(zhuǎn)為GET方式;而后端如果設(shè)置成POST方式了,那就請求不了了。 jsonp的實現(xiàn)方式其實就是<script>腳本請求地址的方式一樣,只是ajax的jsonp對其做了封裝,所以可想而知,jsonp是不支持POST方式的。 1 <%@ page pageEncoding="utf-8" contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>跨域測試</title> 5 <script src="js/jquery-1.7.2.js"></script> 6 <script> 7 8 $(document).ready(function () { 9 10 $("#btn").click(function () { 11 12 $.ajax({ 13 url: "http://localhost:9090/student", 14 type: "POST", //post請求方式 15 dataType: "jsonp", 16 jsonp: "callback", 17 success: function (data) { 18 var result = JSON.stringify(data); 19 $("#text").val(result); 20 } 21 }); 22 }); 23 24 }); 25 </script> 26 </head> 27 <body> 28 <input id="btn" type="button" value="跨域獲取數(shù)據(jù)" /> 29 <textarea id="text" style="width: 400px; height: 100px;"></textarea> 30 </body> 31 </html> 效果圖:
再補充一點,回到第一條:CORS頭缺少“Access-Control-Allow-Origin”。 有時候你會發(fā)現(xiàn)其它都沒問題,出現(xiàn)這個錯誤:這個錯誤代表服務(wù)端拒絕跨域訪問。如果出現(xiàn)這個錯誤,就需要在服務(wù)端設(shè)置允許跨域請求。 response.setHeader("Access-Control-Allow-Origin", "*"); 設(shè)置允許任何域名跨域訪問 設(shè)置可以跨域訪問:第6行代碼或第8行代碼,設(shè)置其中一個即可。 1 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 2 response.setCharacterEncoding("UTF-8"); 3 response.setContentType("text/html;charset=UTF-8"); 4 5 // * 表示允許任何域名跨域訪問 6 response.setHeader("Access-Control-Allow-Origin", "*"); 7 // 指定特定域名可以訪問 8 response.setHeader("Access-Control-Allow-Origin", "http:localhost:8080/"); 9 10 //數(shù)據(jù) 11 List<Student> studentList = getStudentList(); 12 13 JSONArray jsonArray = JSONArray.fromObject(studentList); 14 String result = jsonArray.toString(); 15 16 //前端傳過來的回調(diào)函數(shù)名稱 17 String callback = request.getParameter("callback"); 18 //用回調(diào)函數(shù)名稱包裹返回數(shù)據(jù),這樣,返回數(shù)據(jù)就作為回調(diào)函數(shù)的參數(shù)傳回去了 19 result = callback + "(" + result + ")"; 20 21 response.getWriter().write(result); 22 }
總結(jié):jQuery ajax方式以jsonp類型發(fā)起跨域請求,其原理跟<script>腳本請求一樣,因此使用jsonp時也只能使用GET方式發(fā)起跨域請求??缬蛘埱笮枰?wù)端配合,設(shè)置callback,才能完成跨域請求。 |
|
來自: 眺朢 > 《前端開發(fā)》