Saturday, February 19, 2011

Read query string using Actionscript 3

Today we will learn how to get parameters from query string of the embedded flash file using AS3.

For example, we have a html page:


<html>
<head>
<title>
Hello! Test page!
</title>
</head>
<body>
<object data="get.swf?firstName=Kirill&lastName=Poletaev" 
style="height: 400px; width: 550px;"
type="application/x-shockwave-flash">
<param name="movie" value="get.swf?firstName=Kirill&lastName=Poletaev">
<param name="wmode" value="opaque">
</object>
</body>
</html>

As you can see, we are trying to pass some variables in the query string when telling the path to the flash file. Let's try to read the variables from flash using AS3.

In this example, I created a text field in my flash file to display the data I've received from the query, the text field is called outp.

The first thing we need to do is to get the object that has all the passed variables as parameters. We can do it this way:

var theQuery = root.loaderInfo.parameters;

Now, we might not know how many variables we are meant to receive and what they are called. That's why we check whether the query actually contains anything. If it does - proceed to run through the object using a for...each loop and display the results.

if (theQuery != null)
{
for each (var par in theQuery)
{
outp.appendText(par + "\n");
}
}
else
{
outp.text = "Value is null";
}

When we test our movie in the html page, the textfield will display:

Poletaev
Kirill

Now, if we actually know what variables we are going to receive, we can simply display them like this:

outp.appendText("First name: " + root.loaderInfo.parameters.firstName + "\n");
outp.appendText("Last name: " + root.loaderInfo.parameters.lastName);

And that's how you do it.

Thanks for reading!

No comments:

Post a Comment