JS的跨域問題,我想很多程式員的腦海裡面還認為JS是不能跨域的,其實這是一個錯誤的觀點;有很多人在網上找其解決方法,教其用IFRAME去解決的文章很多,真有那麼複雜嗎?其實很簡單的,如果你用JQUERY,一個GETJSON方法就搞定了,而且是一行代碼搞定。
下面開始貼出方法。
//跨域(可跨所有域名)
| |
| |
| |
注意,getregion.aspx中,在輸出JSON資料時,一定要用Request.QueryString["jsoncallback"],将擷取的内容放到傳回JSON資料的前面,假設實際擷取的值為42342348,那麼傳回的值就是 42342348([{"_name":"湖南省","_regionId":134},{"_name":"北京市","_regionId":143}])
因為getJSON跨域的原理是把?随機變一個方法名,然後傳回執行的,實作跨域響應的目的。
具體getJSON的使用說明,請參考JQUERY手冊。
下面一個是跨域執行的真執行個體子:
| |
| |
| |
| |
| |
轉載自csdn:http://blog.csdn.net/misswuyang/archive/2009/10/23/4718737.aspx
jQuery跨域原理:
浏覽器會進行同源檢查,這導緻了跨域問題,然而這個跨域檢查還有一個例外那就是HTML的<Script>标記;我們經常使用<Script>的src屬性,腳本靜态資源放在獨立域名下或者來自其它站點的時候這裡是一個url;這個url 響應的結果可以有很多種 , 比如 JSON, 傳回的 Json 值成為 <Script> 标簽的 src 屬性值 . 這種屬性值變化并不會引起頁面的影響 . 按照慣例,浏覽器在 URL 的查詢字元串中提供一個參數,這個參數将作為結果的字首一起傳回到浏覽器 ;
看下面的例子:
| |
| |
這種方式被稱作 JsonP ;(如果連結已經失效請點選這裡: JSONP ) ;即:JSON with padding 上面提到的字首就是所謂的“padding”。 那麼 jQuery 裡面是怎麼實作的呢?
貌似并沒有 <Script> 标記的出現!? OKay ,翻看源碼來看:
頁面調用的是getJSON:
| |
| |
| |
7
8 繼續跟進
9
10 get: function ( url, data, callback, type ) {
11 // shift arguments if data argument was omited
12 if ( jQuery.isFunction( data ) ) {
13 type = type || callback;
14 callback = data;
15 data = null ;
16 }
17
18 return jQuery.ajax({
19 type: " GET " ,
20 url: url,
21 data: data,
22 success: callback,
23 dataType: type
24 });
25
26
跟進 jQuery.ajax,下面是 ajax 方法的代碼片段:
1 // Build temporary JSONP function
2 if ( s.dataType === " json " && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
3 jsonp = s.jsonpCallback || ( " jsonp " + jsc ++ );
4
5 // Replace the =? sequence both in the query string and the data
6 if ( s.data ) {
7 s.data = (s.data + "" ).replace(jsre, " = " + jsonp + " $1 " );
8 }
9
10 s.url = s.url.replace(jsre, " = " + jsonp + " $1 " );
11
12 // We need to make sure
13 // that a JSONP style response is executed properly
14 s.dataType = " script " ;
15
16 // Handle JSONP-style loading
17 window[ jsonp ] = window[ jsonp ] || function ( tmp ) {
18 data = tmp;
19 success();
20 complete();
21 // Garbage collect
22 window[ jsonp ] = undefined;
23
24 try {
25 delete window[ jsonp ];
26 } catch (e) {}
27
28 if ( head ) {
29 head.removeChild( script );
30 }
31 };
32 }
33
34 if ( s.dataType === " script " && s.cache === null ) {
35 s.cache = false ;
36 }
37
38 if ( s.cache === false && type === " GET " ) {
39 var ts = now();
40
41 // try replacing _= if it is there
42 var ret = s.url.replace(rts, " $1_= " + ts + " $2 " );
43
44 // if nothing was replaced, add timestamp to the end
45 s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? " & " : " ? " ) + " _= " + ts : "" );
46 }
47
48 // If data is available, append data to url for get requests
49 if ( s.data && type === " GET " ) {
50 s.url += (rquery.test(s.url) ? " & " : " ? " ) + s.data;
51 }
52
53 // Watch for a new set of requests
54 if ( s.global && ! jQuery.active ++ ) {
55 jQuery.event.trigger( " ajaxStart " );
56 }
57
58 // Matches an absolute URL, and saves the domain
59 var parts = rurl.exec( s.url ),
60 remote = parts && (parts[ 1 ] && parts[ 1 ] !== location.protocol || parts[ 2 ] !==location.host);
61
62 // If we're requesting a remote document
63 // and trying to load JSON or Script with a GET
64 if ( s.dataType === " script " && type === " GET " && remote ) {
65 var head = document.getElementsByTagName( " head " )[ 0 ] || document.documentElement;
66 var script = document.createElement( " script " );
67 script.src = s.url;
68 if ( s.scriptCharset ) {
69 script.charset = s.scriptCharset;
70 }
71
72 // Handle Script loading
73 if ( ! jsonp ) {
74 var done = false ;
75
76 // Attach handlers for all browsers
77 script.onload = script.onreadystatechange = function () {
78 if ( ! done && ( ! this .readyState ||
79 this .readyState === " loaded " || this .readyState === " complete " ) ) {
80 done = true ;
81 success();
82 complete();
83
84 // Handle memory leak in IE
85 script.onload = script.onreadystatechange = null ;
86 if ( head && script.parentNode ) {
87 head.removeChild( script );
88 }
89 }
90 };
91 }
92
93 // Use insertBefore instead of appendChild to circumvent an IE6 bug.
94 // This arises when a base node is used (#2709 and #4378).
95 head.insertBefore( script, head.firstChild );
96
97 // We handle everything using the script element injection
98 return undefined;
99 }
100
上面的代碼第1行到第10行:判斷是JSON類型調用,為本次調用建立臨時的JsonP方法,并且添加了一個随機數字,這個數字源于用日期值;
這個地方也就是Taven.李錫遠所說的“随機變一個方法名”;
關注第14行,這一行相當關鍵,注定了我們的結果最終是<Script> ;然後是構造Script片段,第95行在Head中添加該片段,修成正果;
不僅僅是jQuery,很多js架構都是用了同樣的跨域方案,:)說到這裡,嗯,這就是getJSON跨域的原理,趙本山說了“情況呢就是這麼個情況”