Flash/Flex学习笔记(9):ActionScript3.0与Javascript的相互调用
原理跟Silverlight中的几乎如出一辙(见Silverlight如何与JS相互调用):
ActionScript3代码:
01
btnCallJs.addEventListener(MouseEvent.CLICK,fnCallJs);
02
03
function
fnCallJs(e:MouseEvent):
void
{
04
trace
(
"准备调用..."
);
05
//调用js中的JsHello方法,并将返回值显示到Label中
06
lblResult.text=ExternalInterface.call(
"JsHello"
,
"AS3传递的参数"
);
07
}
08
09
function
CalledByJs(p:
String
):
String
{
10
return
"Flash中的CalledByJs被调用了,这是js中传过来的参数:"
+ p;
11
}
12
13
ExternalInterface.addCallback(
"MyFunction"
,CalledByJs);
//这里:MyFunction就是暴露给js调用的方法名称
嵌入flash的页面中这样处理:
01
<
object
classid
=
"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
...
id
=
"Js_AS3"
>
02
... </
object
>
03
04
05
<
script
type
=
"text/javascript"
>
06
function JsHello(msg){
07
var r = "这是js中的方法,参数:" + msg;
08
alert(r);
09
return r;
10
}
11
12
function fnCallAs(msg){
13
var flashObj = document.getElementById("Js_AS3");
14
var sAsReturn = flashObj.MyFunction("js中的参数");
15
alert(sAsReturn);
16
}
17
18
fnCallAs("test");
19
20
</
script
>