Previous Page
Next Page

Recipe 21.5. Handling Flash Remoting Responses

Problem

You want to retrieve a return value from a Flash Remoting method.

Solution

Use a Responder object with call( ).

Discussion

Recipe 21.1 discusses how to use the call( ) method of a NetConnection object to call a Flash Remoting method. The second parameter of that method is designed for specifying how Flash Player should handle responses. If you pass a value of null (as in the examples in that recipe), then no responses are handled. If you want to handle the responses, use a flash.net.Responder object.

The Responder constructor lets you pass it two function references, which handle return values and errors:

var responder:Responder = new Responder(onResult, onError);

When the result function gets called, it's passed one parameter with the value returned by the Flash Remoting method:

private function onResult(returnValue:Datatype):void {
}

The error handler method is passed an object with properties that describe the error in greater detail.

The following example makes a call to a Flash Remoting method called getAverages( ) and uses trace( ) to display the values. The getAverages( ) method returns an associative array with two properties called flash and actionscript:

package {
    import flash.net.NetConnection;
    import flash.net.Responder;

    public class Example {
        private var _connection:NetConnection;
        public function Example(  ) {
            _connection = new NetConnection(  );
            _connection.connect("http://www.rightactionscript.com/flashremoting/                gateway.php");
            var responder:Responder = new Responder(onResult, onError);
            _connection.call("FlashSurvey.getAverages", responder);
        }

        private function onResult(result:Object):void {
            trace(result.flash + " " + result.actionscript);
        }

        private function onError(error:Object):void {
            trace(error.description);
        }
    }
}

When returning values from Flash Remoting methods, you should always return types that serialize well; do not return record sets. Instead, you should always convert record sets to arrays of associative arrays. That ensures the greatest interoperability.

See Also

Recipe 21.4


Previous Page
Next Page
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)