Not yet rated

Problem

A quick and short example of loading data (in this case from a XML file) using the wonderfully simple HTTPService in Flex 3. Thanks to data binding nearly all of the work is done for us. In this simple example I load a very simple XML file into an array and that is displayed in a datagrid with a data source binding to the array of loaded data.

Solution

Sample code loading the XML file and binding a datagrid to display the simple data structure.

Detailed explanation

1. We need to create the HTTPService tag after the application tag in the MXML file.

<mx:HTTPService id="dataSource" url="data/sampledata.xml" result="resultHandler(event)"
fault="faultHandler(event)"/>

2. Next we add a creationComplete event to the Application tag (normally the second line of code in the MXML file).

creationComplete="dataSource.send()"

3. Time for the ActionScript, normally I do not place my code in the MXML file but to keep things simple here it is, just below the HTTPService tag.

<mx:Script>

        <![CDATA[
                import mx.controls.Alert;
                import mx.rpc.events.FaultEvent;
                import mx.rpc.events.ResultEvent;
                import mx.collections.ArrayCollection;

                [Bindable]
                private var loadedData:ArrayCollection;

                private function resultHandler(event:ResultEvent):void
                {
                        this.loadedData = event.result.data.datanode;
                }

                private function faultHandler(event:FaultEvent):void
                {
                        Alert.show("Error: " + event.fault.faultString, "Application Error");
                }
        ]]/>;
</mx:Script>;

Of note here is the bindable variable 'loadedData' that the datagrid will be bound to. Also if an error should occur loading the data I have a popup appear warning us of the problem.

4. Finally we add a datagrid component to display the data.

<mx:DataGrid x="10" y="10" dataProvider="{loadedData}" width="304"/>

+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes