jquery中ajax處理跨域的三大方式

****一、處理跨域的方式:****


1.代理

2.XHR2

HTML5中提供的XMLHTTPREQUEST Level2(及XHR2)已經(jīng)實現(xiàn)了跨域訪問。但ie10以下不支持。只需要在服務(wù)端填上響應(yīng)頭:

header("Access-Control-Allow-Origin:*"); /*星號表示所有的域都可以接受,*/ header("Access-Control-Allow-Methods:GET,POST");

3.jsonp

原理:
ajax本身是不可以跨域的,通過產(chǎn)生一個script標(biāo)簽來實現(xiàn)跨域。因為script標(biāo)簽的src屬性是沒有跨域的限制的。
其實設(shè)置了dataType: 'jsonp'后,$.ajax方法就和ajax XmlHttpRequest沒什么關(guān)系了,取而代之的則是JSONP協(xié)議。JSONP是一個非官方的協(xié)議,它允許在服務(wù)器端集成Script tags返回至客戶端,通過javascript callback的形式實現(xiàn)跨域訪問。
ajax的跨域?qū)懛ǎ?br> (其余寫法和不跨域的一樣):
/當(dāng)前網(wǎng)址是localhost:3000/
js代碼

$.ajax({ type:"get", url:"http://localhost:3000/showAll",/*url寫異域的請求地址*/ dataType:"jsonp",/*加上datatype*/ jsonpCallback:"cb",/*設(shè)置一個回調(diào)函數(shù),名字隨便取,和下面的函數(shù)里的名字相同就行*/ success:function(){ //... } });

/而在異域服務(wù)器上,/
app.js

app.get('/showAll',students.showAll);/*這和不跨域的寫法相同*/ /*在異域服務(wù)器的showAll函數(shù)里,*/ var db = require("./database"); exports.showAll =function(req,res){ /**設(shè)置響應(yīng)頭允許ajax跨域訪問**/ res.setHeader("Access-Control-Allow-Origin","*"); /*星號表示所有的異域請求都可以接受,*/ res.setHeader("Access-Control-Allow-Methods","GET,POST"); var con = db.getCon(); con.query("select * from t_students",function(error,rows){ if(error){ console.log("數(shù)據(jù)庫出錯:"+error); }else{ /*注意這里,返回的就是jsonP的回調(diào)函數(shù)名+數(shù)據(jù)了*/ res.send("cb("+JSON.stringify(r)+")" ); } }

二、解決ajax跨域訪問、 JQuery 的跨域方法

JS的跨域問題,我想很多程序員的腦海里面還認(rèn)為JS是不能跨域的,其實這是一個錯誤的觀點;有很多人在網(wǎng)上找其解決方法,教其用IFRAME去解決的文章很多,真有那么復(fù)雜嗎?其實很簡單的,如果你用JQUERY,一個GETJSON方法就搞定了,而且是一行代碼搞定。

下面開始貼出方法。

//跨域(可跨所有域名) $.getJSON("http://user.hnce.com.cn/getregion.aspx?id=0&jsoncallback=?",function(json){ //要求遠(yuǎn)程請求頁面的數(shù)據(jù)格式為: ?(json_data) //例如: //?([{"_name":"湖南省","_regionId":134},{"_name":"北市","_regionId":143}]) alert(json[0]._name); }); $.getJSON("http://user.hnce.com.cn/getregion.aspx?id=0&jsoncallback=?",function(json){ //要求遠(yuǎn)程請求頁面的數(shù)據(jù)格式為: ?(json_data) //例如: //?([{"_name":"湖南省","_regionId":134},{"_name":"北京市","_regionId":143}]) alert(json[0]._name); });

注意,getregion.aspx中,在輸出JSON數(shù)據(jù)時,一定要用
Request.QueryString["jsoncallback"],將獲取的內(nèi)容放到返回JSON數(shù)據(jù)的前面。假設(shè)實際獲取的值為42342348,那么返回的值就是 42342348([{"_name":"湖南省","_regionId":134},{"_name":"北京市","_regionId":143}])

因為getJSON跨域的原理是把?隨機變一個方法名,然后返回執(zhí)行的,實現(xiàn)跨域響應(yīng)的目的。

下面一個是跨域執(zhí)行的真實例子:

`<script src="http://common.cnblogs.com/script/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
//跨域(可跨所有域名)
$.getJSON("http://e.hnce.com.cn/tools/ajax.aspx?jsoncallback=?", { id: 0, action: 'jobcategoryjson' }, function(json) {
alert(json[0].pid);
alert(json[0].items[0]._name);
});
</script>


<script src="http://common.cnblogs.com/script/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
//跨域(可跨所有域名)
$.getJSON("http://e.hnce.com.cn/tools/ajax.aspx?jsoncallback=?", { id: 0, action: 'jobcategoryjson' }, function(json) {
alert(json[0].pid);
alert(json[0].items[0]._name);
});
</script>`

jQuery跨域原理:
瀏覽器會進(jìn)行同源檢查,這導(dǎo)致了跨域問題,然而這個跨域檢查還有一個例外那就是HTML的<Script>標(biāo)記;我們經(jīng)常使用<Script>的src屬性,腳本靜態(tài)資源放在獨立域名下或者來自其它站點的時候這里是一個url;這個url響應(yīng)的結(jié)果可以有很多種,比如JSON,返回的Json值成為<Script>標(biāo)簽的src屬性值.這種屬性值變化并不會引起頁面的影響.按照慣例,瀏覽器在URL的查詢字符串中提供一個參數(shù),這個參數(shù)將作為結(jié)果的前綴一起返回到瀏覽器;
看下面的例子:

<script type="text/javascript" src="http://domain2.com/getjson?jsonp=parseResponse"> </script>
響應(yīng)值:parseResponse({"Name": "Cheeso", "Rank": 7})
<script type="text/javascript" src="http://domain2.com/getjson?jsonp=parseResponse"> </script>
響應(yīng)值:parseResponse({"Name": "Cheeso", "Rank": 7})

這種方式被稱作JsonP;(如果鏈接已經(jīng)失效請點擊這里:JSONP);即:JSON with padding 上面提到的前綴就是所謂的“padding”。那么jQuery里面是怎么實現(xiàn)的呢?
貌似并沒有<Script>標(biāo)記的出現(xiàn)!?OKay,翻看源碼來看:
頁面調(diào)用的是getJSON:

getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
},

繼續(xù)跟進(jìn)

get: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = null; } return jQuery.ajax({ type: "GET", url: url, data: data, success: callback, dataType: type });

跟進(jìn)jQuery.ajax,下面是ajax方法的代碼片段:

// Build temporary JSONP function if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) { jsonp = s.jsonpCallback || ("jsonp" + jsc++); // Replace the =? sequence both in the query string and the data if ( s.data ) { s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1"); } s.url = s.url.replace(jsre, "=" + jsonp + "$1"); // We need to make sure // that a JSONP style response is executed properly s.dataType = "script"; // Handle JSONP-style loading window[ jsonp ] = window[ jsonp ] || function( tmp ) { data = tmp; success(); complete(); // Garbage collect window[ jsonp ] = undefined; try { delete window[ jsonp ]; } catch(e) {} if ( head ) { head.removeChild( script ); } }; } if ( s.dataType === "script" && s.cache === null ) { s.cache = false; } if ( s.cache === false && type === "GET" ) { var ts = now(); // try replacing _= if it is there var ret = s.url.replace(rts, "$1_=" + ts + "$2"); // if nothing was replaced, add timestamp to the end s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : ""); } // If data is available, append data to url for get requests if ( s.data && type === "GET" ) { s.url += (rquery.test(s.url) ? "&" : "?") + s.data; } // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) { jQuery.event.trigger( "ajaxStart" ); } // Matches an absolute URL, and saves the domain var parts = rurl.exec( s.url ), remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host); // If we're requesting a remote document // and trying to load JSON or Script with a GET if ( s.dataType === "script" && type === "GET" && remote ) { var head = document.getElementsByTagName("head")[0] || document.documentElement; var script = document.createElement("script"); script.src = s.url; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } // Handle Script loading if ( !jsonp ) { var done = false; // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) { done = true; success(); complete(); // Handle memory leak in IE script.onload = script.onreadystatechange = null; if ( head && script.parentNode ) { head.removeChild( script ); } } }; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); // We handle everything using the script element injection return undefined; }

上面的代碼第1行到第10行:判斷是JSON類型調(diào)用,為本次調(diào)用創(chuàng)建臨時的JsonP方法,并且添加了一個隨機數(shù)字,這個數(shù)字源于用日期值;
關(guān)注第14行,這一行相當(dāng)關(guān)鍵,注定了我們的結(jié)果最終是<Script> ;然后是構(gòu)造Script片段,第95行在Head中添加該片段,修成正果;
不僅僅是jQuery,很多js框架都是用了同樣的跨域方案,這就是getJSON跨域的原理。

追加一種解決方式
追求永無止境,在google的過程中,無意中發(fā)現(xiàn)了一個專門用來解決跨域問題的jQuery插件-jquery-jsonp
有第一種方式的基礎(chǔ),使用jsonp插件也就比較簡單了,server端代碼無需任何改動。
來看一下如何使用jquery-jsonp插件解決跨域問題吧。

var url="http://localhost:8080/WorkGroupManagment/open/getGroupById" +"?id=1&callback=?"; $.jsonp({ "url": url, "success": function(data) { $("#current-group").text("當(dāng)前工作組:"+data.result.name); }, "error": function(d,msg) { alert("Could not find user "+msg); } });

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容