19.7.发送变量并处理返回结果

问题
我想发送变量到服务器脚本,并处理返回的结果
解决办法
使用URLLoader.load( )方法且设置URLRequest实例的data属性
讨论
当需要处理服务器返回的结果时,应该使用URLLoader.load( )方法。比如一个flash的商店程序,它的商品分类都存在服务器数据库里,当用户点击一个分类,flash发送这个分类id给服务器脚本并返回这个分类的商品数据。

URLLoader.load( ) 发送数据给服务器脚本的方式和sendToURL( ) ,navigateToURL( ) 是一样的,下面的完整例子发送数据到服务器脚本并返回URL-编码的值:
+展开
-ActionScript
package {
import flash.display.*;
import flash.text.*;
import flash.events.*
import flash.net.*;
public class SendAndLoadExample extends Sprite {
private var _output:TextField;
public function SendAndLoadExample( ) {
initializeOutput( );
sendData( );
}
private function initializeOutput( ):void {
_output = new TextField();
_output.width = stage.stageWidth;
_output.height = stage.stageHeight;
addChild( output );
}
private function sendData( ):Void {
// Create a URLRequest to contain the data to send
// to process.cfm
var request:URLRequest = new URLRequest( "process.cfm" );
// Create name-value pairs to send to the server
var variables:URLVariables = new URLVariables( );
variables.method = "getProductDetail"
variables.productId = 2;
request.data = variables;
// Create a URLLoader to send the data and receive a
// response
var loader:URLLoader = new URLLoader( );
// Expect the script to return URL-encoded variables
loader.dataFormat = DataFormat.VARIABLES;
// Listen for the complete event to read the server response
loader.addEventListener( Event.COMPLETE, handleComplete );
// Send the data in the URLRequest off to the script
loader.load( request );
}
private function handleComplete( event:Event ):void {
var loader:URLLoader = URLLoader( event.target );
// Expect the script to return name and description variables.
// Display these values in a text field on the screen.
_output.text = "Name: " + loader.data.name + "\n"
"Description: " + loader.data.description;
}
}
}

加支付宝好友偷能量挖...


评论(0)网络
阅读(94)喜欢(0)flash/flex/fcs/AIR