咱們常常在Flex程序須要用從外部html向swf文件傳遞參數,(相似 test.html?name=jex&address=chengdu 地址中問號後面的參數對值)html
首 先要明確的是,通常咱們在使用Flex Builder進行Flex開發時,編譯後自動以html容器將swf文件包裝起來了,因此通常來講,咱們直接運行的是html,而非直接運行生成的 swf文件。而Flex應用程序要獲取外部html容器傳入的參數,一般是用JavaScript來獲取到相應參數,再讓javaScript傳遞給 ActionScript。java
在Flex應用程序中,咱們一般要用到ExternalInterface 類,ExternalInterface主要用來讓ActionScript直接與Flash Player容器進行通訊。ExernalInterface類一般做爲ActionScript與JavaScript進行通訊的橋樑。瀏覽器
爲了獲取從html傳入的URL參數,一般傳遞的順序是:html容器—>JavaScript—>ExternalInterface—>ActionScriptide
具體實現:
在Flex中,經過調用ExternalInterface的call方法,參數爲要調用的JavaScript函數,並返回JS函數調用的結果。如:函數
Xml代碼ui
在JS中,Window對象用來表明一個Web瀏覽器窗口,而窗口的Location對象則表明了當前顯示的URL,因而,要想獲取URL中的參數,spa
一般使用下面的語句:xml
Xml代碼htm
注:這裏window屬性引用的Window對象自身,而Window對象的location屬性引用的是Location對象。對象
通 常的參數對以test.html?name=jex&address=chengdu 這樣的形式給出,在獲取到問號後面的URL文本後,還須要 對其分解,這時有兩種途徑,一種是分解過程在JS中完成,而後將最終的結果值傳遞給Flex,另外一種是將分解的過程放在Flex中去完成。在這裏使用的後 者(這樣只需寫AS代碼,而不用去寫JS代碼了^_^)
示例程序代碼以下:
Xml代碼
- <?xml version="1.0" encoding="utf-8"?>
- <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
- creationComplete="init()">
- <mx:Script>
- <![CDATA[
- import mx.controls.Alert;
- private var params:Object;
- private function init():void {
- btnID.addEventListener(MouseEvent.CLICK, clickHandler);
- }
- private function clickHandler(evt:Event):void {
- var args:Object = getParams();
- if(args.name != null && args.address != null) {
- dispID.text = "name:" + args.name + "\n" + "address:" + args.address;
- }
- }
- private function getParams():Object {
- params = {};
- var query:String = ExternalInterface.call("window.location.search.substring", 1);
- // Alert.show(ExternalInterface.call("window.location.href.toString",1));
- // Alert.show(query);
- if(query) {
- var pairs:Array = query.split("&");
- for(var i:uint=0; i < pairs.length; i++) {
- var pos:int = pairs[i].indexOf("=");
- //Alert.show(String(pos));
- if(pos != -1) {
- var argname:String = pairs[i].substring(0, pos);
- var value:String = pairs[i].substring(pos+1);
- params[argname] = value;
- }
- }
- }
- return params;
- }
- ]]>
- </mx:Script>
- <mx:Button id="btnID" y="118" label="GetParams" horizontalCenter="0"/>
- <mx:TextArea id="dispID" y="47" width="200" horizontalCenter="0"/>
- </mx:Application>
轉自:http://hi.baidu.com/fandywang_jlu/item/f8fb14dc951dc04ddcf9bee4