1. 什麼是跨域
我們常在頁面上用 ajax 請求訪問其他伺服器的資料,此時客戶端就會出現跨域問題。跨域問題源自 JavaScript 語言安全限制中的同源策略。
簡單來說,同源策略是指一段腳本只能讀取來自同一來源的窗口與文檔屬性,這裡的「同一來源」指的是主機名、協議與連接埠號的組合。

2. 實現原理
在 HTML DOM 中,script 標籤是可以跨域訪問伺服器資料的。因此可以指定 script 的 src 屬性為跨域的 url,從而實現跨域訪問。
這種訪問方式對返回的資料有個要求:伺服器返回的資料不能是單純的 {"Name":"zhangsan"},否則我們無法引用這個字串。所以要求返回值務必是 var json={"Name":"zhangsan"},或 json({"Name":"zhangsan"})。
為了讓程式不報錯,我們務必還要建立一個 json 函式。
3. 解決方案
方案一
伺服器端:
protected void Page_Load(object sender, EventArgs e) { string result = "callback({\"name\":\"zhangsan\",\"date\":\"2012-12-03\"})"; Response.Clear(); Response.Write(result); Response.End(); }
客戶端:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript"> var result = null; window.onload = function () { var script = document.createElement("script"); script.type = "text/javascript"; script.src = "https://192.168.0.101/ExampleBusinessApplication.Web/web2.aspx"; var head = document.getElementsByTagName("head")[0]; head.insertBefore(script, head.firstChild); }; function callback(data) { result = data; } function b_click() { alert(result.name); } </script> </head> <body> <input type="button" value="click me!" onclick="b_click();" /> </body> </html>
方案二:透過 jQuery 完成
使用 jQuery 的 jsonp 方式,對伺服器端有要求。伺服器端如下:
protected void Page_Load(object sender, EventArgs e) { string callback = Request.QueryString["jsoncallback"]; string result = callback + "({\"name\":\"zhangsan\",\"date\":\"2012-12-03\"})"; Response.Clear(); Response.Write(result); Response.End(); }
客戶端:
$.ajax({ async: false, url: "https://192.168.0.5/Web/web1.aspx", type: "GET", dataType: 'jsonp', //jsonp的值自定義,如果使用jsoncallback,那麼服務器端,要返回一個jsoncallback的值對應的對象. jsonp: 'jsoncallback', //要傳遞的參數,沒有傳參時,也一定要寫上 data: null, timeout: 5000, //返回Json類型 contentType: "application/json;utf-8", //服務器段返回的對象包含name,data屬性. success: function (result) { alert(result.date); }, error: function (jqXHR, textStatus, errorThrown) { alert(textStatus); } });
實際上,執行這段 js 時,js 向伺服器發出了這樣一個請求:
https://192.168.0.5/Web/web1.aspx?jsoncallback=jsonp1354505244726&_=1354505244742
而伺服器也相應返回了如下物件:
jsonp1354506338864({"name":"zhangsan","date":"2012-12-03"})
此時就實現了跨域訪問資料的要求。以上就是 JS 跨域原理與兩種解決方案的介紹,希望對大家學習跨域知識有所幫助。