DIV CSS 佈局教程網

深入淺析 JSONP 解決 Ajax 跨域:從原理到實戰推演
編輯:AJAX基礎知識     

一、先說清楚概念

最近跨域問題遇到得多,正好自己也在看這塊,就順手總結一下。關於 JSONP 的文章網上確實很多,但很多是互相複製,翻來覆去就那麼幾份,關鍵還看不懂。反覆嘗試之後,總算把皮毛弄明白了。這裡要強調一點:用 JSONP 解決跨域,其底層實現其實並不是 Ajax。

同源策略(Same-Origin Policy):瀏覽器的一個重要概念。所謂同源,指域名、協議、端口三者相同。不同源的客戶端腳本(JavaScript、ActionScript)在未明確授權的情況下,不能讀寫對方的資源。

JSONP(JSON with Padding):JSON 的一種「使用模式」,可用於解決主流瀏覽器的跨域數據訪問問題。由於同源策略,位於 server1.example.com 的網頁無法與其他服務器溝通,而 HTML 的 script 元素是一個例外。利用這個開放策略,網頁可以取得其他來源動態產生的 JSON 資料。用 JSONP 抓到的資料不是 JSON,而是任意 JavaScript,由直譯器執行而非 JSON 解析器解析。

二、動手實踐

1. 先複現跨域錯誤

本機起兩個 Tomcat,端口分別為 8080 和 8888,端口不同即滿足非同源條件。兩個項目分別叫 jsonp(8080)與 other(8888)。

jsonp 項目的 index.jsp:

 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <title>Insert title here</title> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript"> function jsonp_fun(){ $.ajax({ url:'https://localhost:8888/other/index.jsp', type:'post', dataType:'text', success:function(data){ console.log(data); } }); } </script> </head> <body> <input type="button" value="jsonp" onclick="jsonp_fun()"/> </body> </html>

other 項目的 index.jsp(JSP 本質就是 Servlet,這裡用它代替 Servlet 演示):

 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <title>Insert title here</title> </head> <body> other domain </body> </html>

點擊按鈕後,Chrome 控制台如實報錯:

XMLHttpRequest cannot load https://localhost:8888/other/index.jsp. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:8080' is therefore not allowed access.

這提示很明確:不能從 8080 這個域去訪問 8888 域的資源。

2. 用 script 標簽跨域加載 js

script 標簽的 src 支援跨域請求,最常見的應用就是 CDN:想用 jQuery 卻沒有本地文件,搜一下 jquery cdn(比如 https://www.bootcdn.cn/jquery/ ),挑個版本貼進項目即可,最大缺點是沒網絡就加載不到。

在 other 根路徑下建 js/other.js:

 alert("this is other(8888) js");

在 jsonp/index.jsp 中引入:

 <script type="text/javascript" src="https://localhost:8888/other/js/other.js"></script>

進入頁面立刻彈出 alert,說明跨域引入的 js 自動執行了。

further,other.js 裡定義的函數,jsonp 頁面同樣能調用——日常開發中的頁面與 js/css 分離就是這個道理。

另外要說明:如果 other.js 中的函數內部用 Ajax 去調 8080 的東西,引入後調用是可以的;但如果它內部調的是 8888 自己的東西,引入之後再調用,同樣是跨域的。跨域判斷看的是發起請求的頁面所處的源,不是腳本文件在哪裡。

3. 用 script 實現真正的跨域取數

先寫好回調函數,再引入遠端腳本去調用它。注意順序:必須先定義函數,後引入腳本,因為 js 是自上而下加載的。

 <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript"> function jsonp_fun(){ $.ajax({ url:'https://localhost:8888/other/index.jsp', type:'post', dataType:'text', success:function(data){ console.log(data); } }); } function getResult(data){ alert(data.result); } </script> <script type="text/javascript" src="https://localhost:8888/other/js/other.js"></script>

other.js 內容:

 getResult({"result":"this is other domain's data"});

也就是:在 jsonp 頁面寫好函數,引入其他域的 js 並在其中調用該函數、傳入參數——這個參數就可以理解為其他域服務器接口返回的數據。刷新頁面,彈出 this is other domain's data。

再往前一步:script 的 src 不僅能接 js 地址,還能接 Servlet 地址,也就是 HTTP 接口地址。新建 other.jsp:

 <%@ page language="java" contentType="text/html; charset=UTF-8"%> <% String params = request.getParameter("params"); out.println("ajax cross success,the server receive params :"+params); %>

jsonp 頁面加入:

 <script type="text/javascript" src="https://localhost:8888/other/other.jsp?params=fromjsonp"></script>

刷新後報錯:Uncaught SyntaxError: Unexpected identifier

代碼有問題嗎?沒有。點開錯誤能看到響應內容確實打印出來了,瀏覽器只是不認識它——因為 script 標簽裡放的是待執行的 JavaScript,而 ajax cross success,the server receive params : jsonp_param 這串裸文本不是合法語法。

換個思路:如果輸出的是 JSON 字串,或者一個調用當前頁面函數的字串(類似前面 3.1 的 getResult({"result":"..."})),問題就解決了。改造 other.jsp:

 <%@ page language="java" contentType="text/html; charset=UTF-8"%> <% String params = request.getParameter("params"); out.println("getResult({'result':'"+params+"'})"); %>

配合頁面中先定義函數、後引入腳本的順序:

 <script type="text/javascript"> function getResult(data){ alert(data.result); } </script> <script type="text/javascript" src="https://localhost:8888/other/other.jsp?params=fromjsonp"></script>

刷新頁面,大功告成。

4. 回調函數名怎麼約定?

還剩一個問題:服務端返回的是 getResult(xxx),這個函數名雙方必須一致。可現實中很多服務是別家公司提供的,難道每個接入方都要去對方公司約定函數名?顯然不可能。

解法也很樸素——把回調函數名作為參數一起傳過去:

 <script type="text/javascript" src="https://localhost:8888/other/other.jsp?params=fromjsonp&callback=getResult"></script>

other.jsp:

 <%@ page language="java" contentType="text/html; charset=UTF-8"%> <% String params = request.getParameter("params"); String callback = request.getParameter("callback"); // 經過該接口一系列操作,然後得到data String data = "{'result':'"+params+"'}"; out.println(callback + "("+data+")"); %>

傳一個回調函數名的參數過去,服務端處理完業務後把數據塞進這個函數的括號裡,調用端預先定義的函數就拿到了數據——作用相當於 Ajax 裡的 success: function(data)。

也可以寫得優雅些,動態創建 script 標簽:

 function CreateScript(src) { $("<script></script>").attr("src", src).appendTo("body") } function jsonp_fun(){ CreateScript("https://localhost:8888/other/other.jsp?params=fromjsonp&callback=getResult") }

5. jQuery 的 JSONP

原理講完了,還是有個問題:手寫看著彆扭。jQuery 其實也是拼一個 script、指定 src,只是封裝得更優雅,調用方式與 Ajax 幾乎一致:

 <script type="text/javascript"> function getResult(data){ alert("through jsonp,receive data from other domain : "+data.result); } function jsonp_fun(){ $.ajax({ url:'https://localhost:8888/other/other.jsp', type:'post', data:{'params':'fromjsonp'}, dataType: "jsonp", jsonp: "callback", //傳遞給請求處理程序的參數名,一般默認為callback jsonpCallback:"getResult", //自定義jsonp回調函數名,不寫則由jQuery自動生成 success: function(data){ }, error: function(){ alert('fail'); } }); } </script> <body> <input type="button" value="jsonp" onclick="jsonp_fun()"/> </body>

設定了 jsonpCallback 為 getResult,返回後會先執行 getResult 中的代碼,再執行 success。實戰中更常見的寫法是不定義 getResult、也不設 jsonpCallback,讓 jQuery 自動生成隨機函數名,只寫 success 即可,用法與普通 Ajax 別無二致:

 function jsonp_fun(){ $.ajax({ url:'https://localhost:8888/other/other.jsp', type:'post', data:{'params':'fromjsonp'}, dataType: "jsonp", jsonp: "callback", success: function(data){ alert("through jsonp,receive data from other domain : "+data.result); }, error: function(){ alert('fail'); } }); }

服務端相應輸出:

 <%@ page language="java" contentType="text/html; charset=UTF-8"%> <% String params = request.getParameter("params"); String callback = request.getParameter("callback"); String data = "{\"result\":\""+params+"\"}"; out.println(callback + "("+data+")"); %>

三、幾點補充認識

1. Ajax 和 JSONP 在調用方式上「看起來」很像,目的也一致——請求一個 url 並處理返回數據,因此 jQuery、Ext 等框架都把 JSONP 作為 Ajax 的一種形式封裝。

2. 但兩者本質不同:Ajax 的核心是用 XMLHttpRequest 獲取非本頁內容,JSONP 的核心是動態添加 script 標簽來調用服務器提供的 js 腳本。

3. 所以說,Ajax 與 JSONP 的區別不在於是否跨域——Ajax 透過服務端代理一樣能跨域,JSONP 本身也不排斥同域數據獲取。

4. 另外,JSONP 只是一種方式或非強制性協議,如同 Ajax 一樣,它並不一定非要用 JSON 格式傳遞數據。你若情願,傳字串也行,只是這樣不利於對外提供公開服務。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved