(1)读取URL传入的参数:类似 test.html?name=jex&address=chengdu 地址中问号后面的参数对值。
思路:在Flex中,通过调用ExternalInterface的call方法,参数为要调用的JavaScript函数,并返回JS函数调用的结果。ExternalInterface.call("JavaScript函数"); 在JS中,Window对象用来代表一个Web浏览器窗口,而窗口的Location对象则代表了当前显示的URL,于是,要想获取URL中的参数,通常使用下面的语句:
window.location.href.toString //得到URL的完整文本
window.location.search.substring //得到问号后面部分的URL文本
- <?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>
(2)FlashVar 传值
flex3中的做法是在html-template下修改index.template.html如下
AC_FL_RunContent(
"src", "${swf}",
"width", "${width}",
"height", "${height}",
"align", "middle",
"id", "${application}",
"quality", "high",
"bgcolor", "${bgcolor}",
"name", "${application}",
"allowScriptAccess","sameDomain",
"type", "application/x-shockwave-flash",
"pluginspage", "http://www.adobe.com/go/getflashplayer",
"flashvars","id=913092672");
然后在as3中使用Application.application.parameters["id"]来调用
Flex4中的设置方法有所改变,还是index.template.html,设置如下
<script type="text/javascript">
<!– For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection. –>
var swfVersionStr = "${version_major}.${version_minor}.${version_revision}";
<!– To use express install, set to playerProductInstall.swf, otherwise the empty string. –>
var xiSwfUrlStr = "${expressInstallSwf}";
var flashvars = {};
flashvars.id= "913092672"; var params = {};
params.quality = "high";
params.bgcolor = "${bgcolor}";
params.allowscriptaccess = "sameDomain";
params.allowfullscreen = "true";
var attributes = {};
attributes.id = "${application}";
attributes.name = "${application}";
attributes.align = "middle";
swfobject.embedSWF(
"${swf}.swf", "flashContent",
"${width}", "${height}",
swfVersionStr, xiSwfUrlStr,
flashvars, params, attributes);
<!– JavaScript enabled so display the flashContent div in case it is not replaced with a swf object. –>
swfobject.createCSS("#flashContent", "display:block;text-align:left;");
</script>
在as3中调用方式也发生了改变
import mx.core.FlexGlobals;
FlexGlobals.topLevelApplication.parameters["id"]
(3)JS互调用:
- <mx:Script>
- <!--[CDATA[
-
- private function initApp():void{
- //添加一个函数,callFlex 供js调用,实际调用的是Flex中的jsCallFlex 函数
- ExternalInterface.addCallback("callFlex",jsCallFlex);
- }
-
- private function callJavaScript():void {
- //Flex调用js函数sayHelloWorld ,并且传递参数params
- ExternalInterface.call("sayHelloWorld","params");
- }
- //真正的供js调用的Flex里的函数
- public function jsCallFlex():void{
- button.label="js call flex successful!";
- }
-
- ]]-->
- </mx:Script>
1、flex中的供js调用函数的注册
ExternalInterface.addCallback("flexfun",jsCallFun);//注册被JS调用的FLEX函数,flexfun为js调用的函数名,jsCallFun为flex实际对应的函数名
2、JS调用代码
var swf = findSWF("swfId");
//传递参数赋值
var tmpObj = {};
tmpObj.inName="name";
tmpObj.inPhone="phone";
swf.flexfun(tmpObj);
function findSWF(movieName) {
if (navigator.appName.indexOf("Microsoft")!= -1) {
return window[movieName];
} else {
return document[movieName];
}
}
(4)中文乱码问题:
flex ->Jsp:
情况一、MXML源代码文件中写入的中文字符:
Flex使用 System.useCodepage = true;即使用本地操作系统编码(GBK) 设置Flex的处理编码。Jsp中用依然用ISO_8859_1 编码来处理,并转化为GBK 。这样Jsp可以正确解释Flex传递的中文字符。 这个时候可以认为Flex对mxml源代码文件进行编译时候,源代码中的中文字符已经混乱了,所以要加上System.useCodepage = true;语句, 按GBK编码将中文字符从Flex发送到Tomcat。
同时Tomcat中Jsp应该按GBK 重新编码
String categoryID = request.getParameter("categoryID");
String strOut = new String(categoryID.getBytes("ISO8859-1 "), "GBK ");
System.out.println("categoryID="+categoryID);
System.out.println("categoryID="+strOut);
情况二、Flex运行时候由输入框输入的中文字符
这个时候输入框输入的中文字符是一定为UTF-8编码的,所以Flex中System.useCodepage = false;或者不设置,就默认utf-8编码格式传递数据,而Tomcat中Jsp使用下面语句按UTF-8来重新编码
String categoryID = request.getParameter("categoryID");
String strOut = new String(categoryID.getBytes("ISO8859-1"), "utf-8");
System.out.println("categoryID="+categoryID);
System.out.println("categoryID="+strOut);
Jsp->Flex:
Jsp页面用页面指令<%@ page contentType="text/html;charset=utf-8"%> 设置,返回结果是utf-8编码,Flex接收后成功解释并正确显示。
通常办法在jsp页面中,加入<% request.setCharacterEncoding("utf-8"); %>,flex默认编码是utf-8。然而,如果问题没有解决,依旧是乱码的话,那么,打开你的tomcat目录下的conf/server.xml文件,观察: <Connector port="8080" protocol="HTTP/1.1"
maxThreads="150" connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8"/>,若没有URIEncoding="UTF-8",添加进去,这样问题就圆满解决了。顺便说下,mysql数据库编码也是utf-8 。
方法1:采用URLVariables对象
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute" fontSize="12"
>
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.rpc.events.ResultEvent;
//对提交给后台的参数进行UTF-8的编码处理
private function httpEncoding(param:String):String{
return encodeURIComponent(param);
}
private function httpEncoding0(param:String):String{
return param;//encodeURI(param);
}
private function doRequest():void{
btn_do.enabled=false;
var url:String = "http://localhost:8600/grid.jsp";
//以下那样写后台会乱码,不管是否做URI编码转换
//url += "?user="+httpEncoding0("用户名");
//url += "&psw="+httpEncoding0("密码");
//trace(url);
srv.url = url;
//srv.send();
//以下这样写正常
var params:URLVariables = new URLVariables();
//这个user,psw就是传入后台的参数user,jsp就用 request.getParameter("user")来取
params.user = httpEncoding("用户名");
params.psw = httpEncoding("密码");
srv.send(params);
}
private function resultHandler(event:ResultEvent):void{
Alert.show("与后台交互结束,前台开始取得的数据...","提示信息");
btn_do.enabled=true;
}
]]>
</mx:Script>
<mx:HTTPService id="srv" result="resultHandler(event);"/>
<mx:Panel title="测试与jsp后台交互" layout="absolute" width="100%" height="90%">
<mx:Button id="btn_do" label="取得数据" click="doRequest();"/>
<mx:Spacer height="1"/>
<mx:DataGrid dataProvider="{srv.lastResult.catalog.product}" width="100%" height="100%" y="28"/>
</mx:Panel>
</mx:Application>
方法2:采用<mx:request/>,同时也演示了mx:State的用法
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:states>
<mx:State name="Logged In">
<mx:SetProperty target="{panel1}" name="width" value="95%"/>
<mx:SetProperty target="{panel1}" name="height" value="95%"/>
<mx:RemoveChild target="{password}"/>
<mx:RemoveChild target="{username}"/>
<mx:RemoveChild target="{label1}"/>
<mx:RemoveChild target="{Submit}"/>
<mx:RemoveChild target="{label2}"/>
<mx:SetProperty target="{panel1}" name="title" value="Members Section"/>
<mx:AddChild relativeTo="{panel1}" position="lastChild">
<mx:Label x="10" y="10" text="Welcome to the Members Section!"/>
</mx:AddChild>
<mx:AddChild relativeTo="{panel1}" position="lastChild">
<mx:Label x="10" y="36" text="Here you can do great things, like join the forums @ Viper Creations!"/>
</mx:AddChild>
<mx:AddChild relativeTo="{panel1}" position="lastChild">
<mx:Label x="10" y="62" text="Label"/>
</mx:AddChild>
</mx:State>
</mx:states>
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
]]>
</mx:Script>
<mx:Script>
<![CDATA[
private function checkLogin(evt:ResultEvent):void
{
if(evt.result.loginsuccess == "yes")
{
currentState = "Logged In";
}
if(evt.result.loginsuccess == "no")
{
mx.controls.Alert.show(''Invalid username/password'');
}
}
]]>
</mx:Script>
<mx:HTTPService id="login_user" result="checkLogin(event)" showBusyCursor="true" method="POST" url="http://www.vipercreations.com/site_admin/login.php" useProxy="false">
<mx:request xmlns="">
<username>
{username.text}
</username>
<password>
{password.text}
</password>
</mx:request>
</mx:HTTPService>
<mx:Panel resizeEffect="Resize" width="250" height="200" layout="absolute" title="Login System" horizontalCenter="0" verticalCenter="-2" id="panel1">
<mx:Label x="10" y="10" text="Username:" id="label1"/>
<mx:TextInput x="10" y="36" id="username"/>
<mx:Label x="10" y="66" text="Password:" id="label2"/>
<mx:TextInput x="10" y="92" id="password" displayAsPassword="true"/>
<mx:Button x="10" y="122" label="Submit" id="Submit" click="login_user.send();"/>
</mx:Panel>
</mx:Application>