Flex 与 javascript交互
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" creationComplete="initApp();"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Declarations>
<!-- 将非可视元素(例如服务、值对象)放在此处 -->
</fx:Declarations>
<fx:Script>
<![CDATA[
//Flex
import flash.external.ExternalInterface;
import mx.controls.Alert;
public function javaScriptFun(value:String):String{
return "调用Flex函数成功1" + value;
}
public function initApp():void{
ExternalInterface.addCallback("myFlexFun",javaScriptFun);
btn.addEventListener(MouseEvent.CLICK, callJs);
}
public function callJs(event:MouseEvent):void{
//应该如何召唤javascript函数?
var str:String = ExternalInterface.call("sendToFlex","Flex");
if(str == null){
Alert.show("召唤失败");
}else{
Alert.show(str);
}
}
]]>
</fx:Script>
<s:Button x="204" y="173" label="召唤JavaScriptFun" id="btn" width="153"/>
</s:Application>
<script type="text/javascript">
window.onload = function () {
document.getElementById("swfHtml").innerHTML = getSWFHTML();
}
function callApp() {
var x;
if (navigator.appName.indexOf("Microsoft") != -1) {
x = document.getElementById("MyFlexApp").myFlexFun();
//x = document.getElementById("MyFlexApp").myFlexFun("test"); 这样传递参数出错,应该如何传参?
}
else {
x = document.getElementById("MyFlexApp").myFlexFun();
}
alert(x);
}
function getSWFHTML() {
var swfNode = "";
if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) {
// Netscape浏览器插件体系结构
swfNode = '<embed type="application/x-shockwave-flash" src="flex/FlexProject2.swf" ';
swfNode += 'id="MyFlexApp" name="MyFlexApp" ';
swfNode += 'allowScriptAccess="sameDomain" ';
swfNode += 'FlashVars ="param1=one¶m2=2¶m3=3¶m4=four"';
swfNode += '/>';
} else { // IE
swfNode = '<object id="MyFlexApp" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">';
swfNode += '<param name="movie" value="flex/FlexProject2.swf" />';
swfNode += '<param name="FlashVars" value="param1=one¶m2=2¶m3=3¶m4=four" />';
swfNode += '<param name="allowScriptAccess" value="sameDomain" />';
swfNode += "</object>";
}
return swfNode;
}
function sendToFlex(value) {
return "返回给Flex值:" + value;
}
</script>
<input onclick="callApp();" value="调用Flex" type="button" />