Flex 与 JavaScript 交互,主要依靠Flex的ExternalInterface,其提供了addCallBack和call方法.
下面的例子将演示Flex调用javascript,和javascript调用Flex
javascript代码:
代码
function hello(param) {
alert(param);
return "jsp Hello:" + param;
}
function callFlexFunction() {
var x = document.getElementById("flexObject").flexHelloWorld("Hello", "world");
alert(x);
}
alert(param);
return "jsp Hello:" + param;
}
function callFlexFunction() {
var x = document.getElementById("flexObject").flexHelloWorld("Hello", "world");
alert(x);
}
Flex代码:
代码
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
initialize="initApp()">
<mx:Script>
<![CDATA
import mx.controls.Alert;
public function flexHelloWorld(param1:String, param2:String):String {
Alert.show("param1: " + param1 + "; param2:" + param2);
return "Hello " + param1 + param2;
}
public function initApp():void {
ExternalInterface.addCallback("flexHelloWorld", flexHelloWorld);
}
public function jspHello():void {
var s:String = ExternalInterface.call("hello", "Flex");
Alert.show(s);
}
]]>
</mx:Script>
<mx:Button x="52" y="58" label="call javascript" click="jspHello()"/>
</mx:Application>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
initialize="initApp()">
<mx:Script>
<![CDATA
import mx.controls.Alert;
public function flexHelloWorld(param1:String, param2:String):String {
Alert.show("param1: " + param1 + "; param2:" + param2);
return "Hello " + param1 + param2;
}
public function initApp():void {
ExternalInterface.addCallback("flexHelloWorld", flexHelloWorld);
}
public function jspHello():void {
var s:String = ExternalInterface.call("hello", "Flex");
Alert.show(s);
}
]]>
</mx:Script>
<mx:Button x="52" y="58" label="call javascript" click="jspHello()"/>
</mx:Application>