I recently got a question about what the ActionScript 3.0 equivalent is of the LoadVars sendAndLoad method. It may look like a lot more typing (and it is) but the whole implementation is very clean by separating out the request, loader and variables which you can only benefit from in the long run.

import flash.events.Event;
import flash.net.*;

var myRequest:URLRequest = new URLRequest("http://www.myserver.com/myscript.php");
var myLoader:URLLoader = new URLLoader();
var myVariables:URLVariables = new URLVariables();

myVariables.firstProperty = "first";
myVariables.secondProperty = "second";

myRequest.method = URLRequestMethod.GET;
myRequest.data = myVariables;

function onLoaded(evt:Event):void {
  trace("here we get the data back: "+myLoader.data);
}

myLoader.addEventListener(Event.COMPLETE, onLoaded);
myLoader.load(myRequest);

What happens in the code above is we set up a URLRequest instance that points to the server side resource you want to target. Next an instance of the URLLoader class is instantiated and we assign an instance of the URLVariables class to its data property.

This URLVariables instance basically abstracts the name/value pairs you want to send to the server. Since we specified the method of our URLRequest instance to use GET calling the load request essentially is equivalent to calling the following URL in your browser:

http://www.myserver.com/myscript.php?firstProperty=first&secondProperty=second

Finally before calling this load method we add an event listener to the URLLoader instance and set up a function to listen for the data we get back from the server side script.

That's all cool, but what if you want to send an XML file your server side script (some JSON for example) instead of name/value pairs? Well no big deal, you can simply leave out the URLVariables instance and set the contentType property of the URLRequest instance to "text/xml" and assign your XML directly to the data property.

import flash.events.Event;
import flash.net.*;

var myRequest:URLRequest = new URLRequest("http://www.myserver.com/myscript.php");
var myLoader:URLLoader = new URLLoader();

var myXML:XML = Hello World;

myRequest.contentType = "text/xml";
myRequest.data = myXML;

function onLoaded(evt:Event):void {
  trace("here we get the data back: "+myLoader.data);
}

myLoader.addEventListener(Event.COMPLETE, onLoaded);
myLoader.load(myRequest);
Posted
AuthorPeter
CategoriesFlash, Flex