天天看點

Flex+Struts2+JSON 實作異部送出

Flex+Struts2+JSON的背景代碼我在這就不多說了。不懂得請看我寫的上一篇文章《Struts2+JQuery+JSON實作異步互動》那篇文章,背景沒有任何變化。

在這着重講Flex端的實作代碼。

第一步:

從http://code.google.com/p/as3corelib/網站中下載下傳as3corelib-.92.1.zip檔案并解壓,解壓後在as3corelib-.92.1\as3corelib-.92.1\lib目錄中有一個as3corelib.swc檔案,把該檔案複制到你的Flex工程的libs目錄中。就可以工作了。請看Flex代碼:

Flex代碼代碼

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

<mx:Application xmlns:mx="<A href="http://www.adobe.com/2006/mxml" target="_blank" rel="external nofollow" >http://www.adobe.com/2006/mxml</A>" fontSize="12" layout="absolute">

<mx:Script>

<![CDATA[

import com.adobe.serialization.json.JSONDecoder;

import mx.rpc.events.FaultEvent;

import mx.controls.Alert;

import mx.rpc.events.ResultEvent;

internal function sendURL():void{

//設定HTTPService的url屬性為你要通路的Action連接配接後面dd=new Date().getTime();是為了消除浏覽器緩存

hs.url = "<A href="http://localhost:8080/fsj/flexstrutsjson!hdList.action?dd=%22+new" target="_blank" rel="external nofollow" >http://localhost:8080/fsj/flexstrutsjson!hdList.action?dd="+new</A> Date().getTime();

//調用HTTPService的send()方法

hs.send();

//注冊成功事件

hs.addEventListener(ResultEvent.RESULT,success);

//注冊失敗事件

hs.addEventListener(FaultEvent.FAULT,faultResult);

}

//失敗事件調用的函數

internal function faultResult(event:FaultEvent):void{

//彈出失敗資訊

Alert.show(event.fault.message);

}

//成功函數

internal function success(event:ResultEvent):void{

//把傳回的對象轉換成字元串

var userStr:String = event.result.toString();

//使用剛才加入的swc包包中的類JSONDecoder()把字元串轉換成JSONDecoder對象

var userJson:JSONDecoder = new JSONDecoder(userStr);

//傳回Map的方式

// var d:Object = userJson.getValue().uerInfoMap;

// var arryObject:Array=[];

// for each(var f:Object in d){

// arryObject.push(f);

// }

// userInfo.dataProvider = arryObject;

//傳回List的處理方式

//使用JSONDecoder對象的getValue方法傳回對象

userInfo.dataProvider = userJson.getValue().userInfos;

}

]]>

</mx:Script>

<!--建立HTTPService對象-->

<mx:HTTPService id="hs" method="POST" showBusyCursor="true"/>

<!--建立發送按鈕并調用sendURL()函數-->

<mx:Button id="requstDate" click="sendURL()" label="發送" x="95" y="78"/>

<!--建立DataGrid控件來綁定傳回的資料-->

<mx:DataGrid x="95" y="131" width="482" height="270" id="userInfo">

<mx:columns>

<mx:DataGridColumn headerText="使用者名" dataField="userName"/>

<mx:DataGridColumn headerText="密碼" dataField="pwd"/>

<mx:DataGridColumn headerText="Email" dataField="email"/>

<mx:DataGridColumn headerText="年齡" dataField="age"/>

</mx:columns>

</mx:DataGrid>

</mx:Application>