如果只是 GET 的話,解決方案要多一些,JSONP 之類都可以。
POST 麻煩一點,在網上搜了一圈,解決方案挺多的,感覺這種利用Flash做代理的方案還是比較不錯的,瀏覽器安全色性也很好,但前提是 Web Server 是你自己在管理,因為基於Flash的安全規則,需要在網站的根目錄放一個 crossdomain.xml,我這裡就全部允許了:
<?xml version="1.0"?><br /><!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd"><br /><!-- Policy file for xmlsocket://socks.mysite.com --><br /><cross-domain-policy><br /> <site-control permitted-cross-domain-policies="master-only" /><br /> <allow-access-from domain="*" /><br /> <allow-http-request-headers-from domain="*" headers="*" /><br /></cross-domain-policy>
我看到國內也有開發人員自己封裝的,不過和這個比起來還有些差距,建議使用這個,他針對Prototype, Dojo, JQuery 都做了外掛程式,真的很方便:
http://flxhr.flensed.com/
以 JQuery 為例:
1. 首先下載flxhr 及相應的 JQuery 外掛程式:
a> http://flxhr.flensed.com/code/releases/jquery/jquery.flXHRproxy.js
b> http://plugins.jquery.com/project/XHR
c> http://flxhr.flensed.com/download.php
2. 頁面嵌入相應的指令碼:
<script type="text/javascript" src="xxx/flXHR.js"></script>
<script type="text/javascript" src="xxx/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="xxx/jquery.xhr.js"></script>
<script type="text/javascript" src="xxx/jquery.flXHRproxy.js"></script>
3. 範例代碼:var usecount = 0;jQuery(document).ready(function() {jQuery.flXHRproxy.registerOptions("http://test.getify.com/flXHR-tests/",{xmlResponseText:false,loadPolicyURL:"http://test.getify.com/flXHR-tests/policy.php"});});function doit() {var count = (usecount+1);for (var i=0; i<count; i++) {var requestbody = "My name is jQuery-Test (#"+(++usecount)+")";jQuery.ajaxSetup({transport:'flXHRproxy',error:handleError});jQuery.post("http://test.getify.com/flXHR-tests/textme.php",requestbody,handleLoading,"text/plain");}}function handleLoading(data,status,XHRobj) {if (XHRobj.readyState == 4) {alert("readyState:"+XHRobj.readyState+"/nresponseText:"+XHRobj.responseText+"/nstatus:"+XHRobj.status+"/nstatusText:"+XHRobj.statusText+"/nSource Object Id: "+XHRobj.instanceId);}}function handleError(XHRobj,errtype,errObj) {alert("Error: "+errObj.number+"/nType: "+errObj.name+"/nDescription: "+errObj.description+"/nSource Object Id: "+errObj.srcElement.instanceId);}