Dynamic Post: posting name value pairs from flash to a web server
I wanted to build a function which would accept 2 arrays and a URL. The first array holds the names of the data you are posting. The second array holds the values. The reason to use this type of function would be if you have multiple posts from the swf to your webserver.
So in ActionScript 3.0 (this is a simplified version for clarity):
private function somefunction():void
{
//these are the names of the variable sent in the post
//note that the number of name:value pairs MUST MATCH!
variableNamesArray[0] = "first_name";
variableNamesArray[1] = "middle_name";
variableNamesArray[2] = "last_name";
//the data held in the post variables
saveDataArray[0] = "Bob";
saveDataArray[1] = "Martin";
saveDataArray[2] = "Westerfield";
data_post("somescript.html", variableNamesArray, saveDataArray);
}
public function data_post(thisUrl:String, varArray:Array, dataArray:Array)
{
var i:int;
var loader:URLLoader = new URLLoader();
var r:URLRequest = new URLRequest(thisUrl);
var v:URLVariables = new URLVariables();
//this holds the name=value pairs in a string
var nvpString:String = "";
//loop thru varArray and put var name and data into post variables
for(i=0; i < varArray.length; i++)
{
//create name value pairs
nvpString += varArray[i] + "=" + escape(dataArray[i]) + "&";
}
r.data = nvpString;
r.method = URLRequestMethod.POST;
loader.load(r);
loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
loader.addEventListener(Event.COMPLETE, loaderCompleteHandler);
}
Copyright Gary Rosenzweig
