User Guide
378 Networking and Communication
Communicating with external scripts
In addition to loading external data files, you can also use the URLVariables class to send
variables to a server-side script and process the server’s response. This is useful, for example, if
you are programming a game and want to send the user’s score to a server to calculate whether
it should be added to the high scores list, or even send a user’s login information to a server for
validation. A server-side script can process the user name and password, validate it against a
database, and return confirmation of whether the user-supplied credentials are valid.
The following snippet creates a URLVariables object named
variables, which creates a new
variable called
name. Next, a URLRequest object is created that specifies the URL of the
server-side script to send the variables to. Then you set the
method property of the
URLRequest object to send the variables as an HTTP
POST request. To add the URLVariables
object to the URL request, you set the
data property of the URLRequest object to the
URLVariables object created earlier. Finally, the URLLoader instance is created and the
URLLoader.load() method is invoked, which initiates the request.
var variables:URLVariables = new URLVariables("name=Franklin");
var request:URLRequest = new URLRequest();
request.url = "http://www.[yourdomain].com/greeting.cfm";
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, completeHandler);
try
{
loader.load(request);
}
catch (error:Error)
{
trace("Unable to load URL");
}
function completeHandler(event:Event):void
{
trace(event.target.data.welcomeMessage);
}
The following code contains the contents of the ColdFusion® greeting.cfm document used in
the previous example:
<cfif NOT IsDefined("Form.name") OR Len(Trim(Form.Name)) EQ 0>
<cfset Form.Name = "Stranger" />
</cfif>
<cfoutput>welcomeMessage=#UrlEncodedFormat("Welcome, " & Form.name)#
</cfoutput>