使用JSON服务
Flex是用Flash播放器的编程语言ActionScript 3编写的。它和JavaScript很类似,但它没有eval方法。那么我们如何将JSON文本转换成ActionScript数据呢?幸运的是,免费的ActionScript 3核心库(http://as3corelib.googlecode.com)包含了JSON解码器和JSON编码器。
列表7中的代码演示了JSONDecoder对象的用法:
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="jsonservice.send()"> <mx:Script> <![CDATA[ import mx.rpc.events.ResultEvent; import com.adobe.serialization.json.JSONDecoder; private function onJSONResult( event:ResultEvent ) : void { var data:String = event.result.toString(); data = data.replace( /\s/g, '' ); var jd:JSONDecoder = new JSONDecoder( data ); dg.dataProvider = jd.getValue(); } ]]> </mx:Script> <mx:HTTPService id="jsonservice" url="http://localhost:8080/jsp-examples/flexds/json.jsp" resultFormat="text" result="onJSONResult(event)" /> <mx:Panel title="Stock Data " width="100% " height="100% "> <mx:DataGrid id="dg" width="100%" height="100%"> <mx:columns> <mx:DataGridColumn dataField="compa " /> <mx:DataGridColumn dataField="compb " /> </mx:columns> </mx:DataGrid> </mx:Panel> </mx:Application><?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="jsonservice.send()"> <mx:Script> <![CDATA[ import mx.rpc.events.ResultEvent; import com.adobe.serialization.json.JSONDecoder; private function onJSONResult( event:ResultEvent ) : void { var data:String = event.result.toString(); data = data.replace( /\s/g, '' ); var jd:JSONDecoder = new JSONDecoder( data ); dg.dataProvider = jd.getValue(); } ]]> </mx:Script> <mx:HTTPService id="jsonservice" url="http://localhost:8080/jsp-examples/flexds/json.jsp" resultFormat="text" result="onJSONResult(event)" /> <mx:Panel title="Stock Data " width="100% " height="100% "> <mx:DataGrid id="dg" width="100%" height="100%"> <mx:columns> <mx:DataGridColumn dataField="compa " /> <mx:DataGridColumn dataField="compb " /> </mx:columns> </mx:DataGrid> </mx:Panel> </mx:Application>