Saturday, July 28, 2007

Loading name/value pairs using the mx:HTTPService tag

original author : Peter deHaan

source: Peter deHaan's blog

== quote from his blog ==
<?xml version="1.0" encoding="utf-8"?>

<
mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal" verticalAlign="middle" backgroundColor="white" creationComplete="httpParams.send()">

<
mx:HTTPService resultFormat="flashvars" url="{VARIABLES_URL}" id="httpParams" result="onResult(event)" />

<
mx:Script>

<![
CDATA[
import
mx.rpc.events.ResultEvent;

import
mx.collections.ArrayCollection;

[
Bindable]
private var
VARIABLES_URL:String = "params.txt";

[
Bindable]

private var
paramColl:ArrayCollection = new ArrayCollection();

private function
onResult(evt:ResultEvent):void {

var
vars:Object = evt.result;
var
key:String;

for
(key in vars) {

paramColl.addItem({key:key, value:vars[key]});
}


params.visible = true;
}
]]>
</
mx:Script>

<
mx:VBox>

<
mx:Label text="Parameters:" />
<
mx:DataGrid id="params" dataProvider="{paramColl}" rowCount="5" visible="false">

<
mx:columns>
<
mx:DataGridColumn dataField="key" headerText="Key" />

<
mx:DataGridColumn dataField="value" headerText="Value" />
</
mx:columns>

</
mx:DataGrid>
</
mx:VBox>

</
mx:Application>



Again, I’m sure there is a nicer way of handling the ResultEvent and converting to a data provider, so you may want to play around with it a bit.

Of course, if you know the names of the parameters in the file that you’re loading, you could also just do something like this:

<?xml version="1.0" encoding="utf-8"?>

<
mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white" creationComplete="httpService.send()">

<
mx:HTTPService id="httpService" resultFormat="flashvars" url="params.txt" />

<
mx:VBox>

<
mx:Label text="name: {httpService.lastResult.name}" />
<
mx:Label text="product: {httpService.lastResult.product}" />

<
mx:Label text="powermove: {httpService.lastResult.powermove}" />
<
mx:Label text="skill: {httpService.lastResult.skill}" />

</
mx:VBox>

</
mx:Application>


Oh, and remember, since the params.txt file is being loaded at run-time and embedded during compile-time, the params.txt file needs to be relative to the SWF file and not the MXML file.

2 comments:

peterd said...

Is there a reason you're stealing all my content?

http://blog.flexexamples.com/2007/07/28/loading-namevalue-pairs-using-the-mxhttpservice-tag/

That kind of isn't cool. I work kind of hard to try and come up with some original content.

Unknown said...

sorry about that, i just saw your comments, although i do include source "here" at the top to link to your original post, i should mention the original author.

I grab useful posts from internet and put them in my blog to easy access, but I really
should include author's name.