文章目錄
非同步http請求的跨域問題,google一下已經有好幾種解決方案了,像是JSONP、window.name等方式,沒細看,感覺都挺麻煩的。
無意中看到一種借用CSSHttpRequest的方式(相對應於XmlHttpRequest),藉助於web頁面對css的請求無domain限制的原理,在server端將需要的資料編碼成css方式返回給client,而client藉助js來解碼資料並執行相應操作,ok啦,簡單、方便。http://nb.io地址可能是訪問不了的,把文章貼出來(google):
nb.io
CSSHttpRequest is cross-domain AJAX using CSS.
- Cross-browser —supports IE6+, Firefox 2+, Safari 3+, iPhone.
- 100% JavaScript —no Flash required.
- Small —2.4KB minified.
Like JavaScript includes, this works because CSS is not subject to the same-origin policy that affects XMLHttpRequest. CSSHttpRequest functions similarly to JSONP , and is limited to making GET requests. Unlike JSONP, untrusted third-party JavaScript cannot execute in the context of the calling page.
A request is invoked using the CSSHttpRequest.get(url, callback) function:
CSSHttpRequest.get( "http://www.nb.io/hacks/csshttprequest/hello-world/",
function(response) { alert(response); } );
Data is encoded on the server into URI-encoded 2KB chunks and serialized into CSS rules with a modified data: URI scheme. The selector should be in the form #c<N> , where N is an integer index in [0,]. The response is decoded and returned to the callback function as a string:
#c0 { background: url(data:,Hello%20World!); }
#c1 { background: url(data:,I’m%20text%20encoded%20in%20CSS!); }
#c2 { background: url(data:,I%20like%20arts%20and%20crafts.); }
CSSHttpRequest * is open source under an Apache License (Version 2.0).
* Or as Eric refers to it, AJACSS (slightly more electro). * Or as Eric refers to it, AJACSS (slightly more electro).
Examples Examples.
- Hello World
- Lorem Ipsum
- Time (text)
- Time (JSON)
- Flickr tag search (JSON)
源碼在github上的:http://github.com/nbio/csshttprequest/tree/master, 目前有Python/Ruby/PHP的server端實現(即編碼功能),抽時間可以做一下其他實現,如.NET