cross-domain ajax with jQuery and flash-based SWFHttpRequest

by Martin Monperrus Tags:

Flash is a good solution to enable cross-domain ajax with http post (see [[http://engin.bzzzt.biz/2010/03/31/cross-domain-data-push-methods-compared/|this post]] and [[cross-domain ajax with http post for sending large amount of data]]). Yahoo uses it in the YUI framework ([[http://developer.yahoo.com/yui/connection/#xdr]]).

[[http://www.jimbojw.com/wiki/index.php?title=SWFHttpRequest_Flash/Ajax_Utility|SWFHttpRequest]] is an implementation of this technique which is very good because: * it is API compatible with XmlHttpRequest * it is open-source (code written in [[http://haxe.org/|haxe]]), compilable with an open source compiler (no Adobe in the loop). * it is very lightweight (just one SWF file!) In my opinion, the two last points make SWFHttpRequest better than [[http://flxhr.flensed.com/|flxhr]].

As a result, SWFHttpRequest and jQuery go very well together:
$.ajax({
 url: JSKOMMENT.url+'/p/',
 type: 'post',
 /*see [[http://www.jimbojw.com/wiki/index.php?title=SWFHttpRequest_Flash/Ajax_Utility|SWFHttpRequest documentation]] or use [[http://code.google.com/p/swfobject/|swfobject]] to load the SWF file*/
 xhr: function(){return new SWFHttpRequest();},
 data: mydata
 success: function(val){
       ...;
    }
});
Warning: To enable POST with Flash v10, ‘’crossdomain.xml’’ must contain a directive ‘’allow-http-request-headers-from domain’’:
<cross-domain-policy>
  <allow-http-request-headers-from domain="*" headers="*"/> 
  <allow-access-from domain="*" />
</cross-domain-policy>

To enable serving the SWF file from another domain, one must add ’’flash.system.Security.allowDomain("*");’’ to the main of SWFHttpRequest.hx.