?我们经常在Flex程序需要用从外部html向swf文件传递参数,(类似 test.html?name=jex&address=chengdu 地址中问号后面的参数对值)
首 先要明确的是,一般我们在使用Flex Builder进行Flex开发时,编译后自动以html容器将swf文件包装起来了,所以一般来说,我们直接运行的是html,而非直接运行生成的 swf文件。而Flex应用程序要获取外部html容器传入的参数,通常是用JavaScript来获取到相应参数,再让javaScript传递给 ActionScript。
在Flex应用程序中,我们通常要用到ExternalInterface 类,ExternalInterface主要用来让ActionScript直接与Flash Player容器进行通信。ExernalInterface类通常作为ActionScript与JavaScript进行通信的桥梁。
为了获取从html传入的URL参数,通常传递的顺序是:html容器—>JavaScript—>ExternalInterface—>ActionScript
?
具体实现:
在Flex中,通过调用ExternalInterface的call方法,参数为要调用的JavaScript函数,并返回JS函数调用的结果。如:
Xml代码
- ExternalInterface.call("JavaScript函数");??
?
在JS中,Window对象用来代表一个Web浏览器窗口,而窗口的Location对象则代表了当前显示的URL,于是,要想获取URL中的参数,
通常使用下面的语句:
?
Xml代码
- window.location.href.toString?? //得到URL的完整文本??
- ???
- window.location.search.substring //得到问号后面部分的URL文本??
?
注:这里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