1.甚么是跨域
我們常常會在頁面上使用ajax要求訪問其他服務器的數(shù)據(jù),此時,客戶端會出現(xiàn)跨域問題.
跨域問題是由于javascript語言安全限制中的同源策略釀成的.
簡單來講,同源策略是指1段腳本只能讀取來自同1來源的窗口和文檔的屬性,這里的同1來源指的是主機名、協(xié)議和端口號的組合.
例如:
2.實現(xiàn)原理
在HTML DOM中,Script標簽是可以跨域訪問服務器上的數(shù)據(jù)的.因此,可以指定script的src屬性為跨域的url,從而實現(xiàn)跨域訪問.
例如:
這類訪問方式是不行的.但是以下方式,卻是可以的.
這里對返回的數(shù)據(jù)有個要求,即:服務器返回的數(shù)據(jù)不能是單純的如{“Name”:”zhangsan”}
如果返回的是這個json字符串,我們是沒有辦法援用這個字符串的.所以,要求返回的值,務必是var json={“Name”:”zhangsan”},或json({“Name”:”zhangsan”})
為了使程序不報錯,我們務必還要建立個json函數(shù).
3.解決方案
方案1
服務器端:
protected void Page_Load(object sender, EventArgs e)
{
string result = "callback({"name":"zhangsan","date":"2012⑴2-03"})";
Response.Clear();
Response.Write(result);
Response.End();
}
客戶端:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://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 = "http://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>
方案2,通過jquery來完成
通過jquery的jsonp的方式.使用此方式,對服務器端有要求.
服務器端以下:
protected void Page_Load(object sender, EventArgs e)
{
string callback = Request.QueryString["jsoncallback"];
string result = callback + "({"name":"zhangsan","date":"2012⑴2-03"})";
Response.Clear();
Response.Write(result);
Response.End();
}
客戶端:
$.ajax({
async: false,
url: "http://192.168.0.5/Web/web1.aspx",
type: "GET",
dataType: 'jsonp',
//jsonp的值自定義,如果使用jsoncallback,那末服務器端,要返回1個jsoncallback的值對應的對象.
jsonp: 'jsoncallback',
//要傳遞的參數(shù),沒有傳參時,也1定要寫上
data: null,
timeout: 5000,
//返回Json類型
contentType: "application/json;utf⑻",
//服務器段返回的對象包括name,data屬性.
success: function (result) {
alert(result.date);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
實際上,在我們履行這段js時,js向服務器發(fā)出了這樣1個要求:
http://192.168.0.5/Web/web1.aspx?jsoncallback=jsonp1354505244726&_=1354505244742
而服務器也相應的返回了以下對象:
jsonp1354506338864({"name":"zhangsan","date":"2012⑴2-03"})
此時就實現(xiàn)了跨域范文數(shù)據(jù)的要求.