1.Flex里面使用ExternalInterface.call(“Js函数名称”,参数)进行调用javascript方法,其返回的值就是Js函数所返回的值。
2.在初始化方法中使用ExternalInterface.addCallback(“注册的方法名”,As中的函数名)进行注册,“注册的方法名”可以再javascript中直接调用
3.在js中,就可以用document.getElementById(“Flash在Html中的ID”).注册的方法名(参数)进行调用,当然,默认”Flash在Html中的ID”就是Flex文件的名称,例如,我们这里就是SampleApp,因为我们的Flex文件就是SampleApp.mxml
//Flex代码
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="application1_creationCompleteHandler(event)"
minWidth="955" minHeight="600">
<fx:Script>
<![CDATA[
import flash.external.*;
import mx.controls.Alert;
import mx.events.FlexEvent;
protected function text_clickHandler(event:MouseEvent):void
{
myFunc();
}
public function myFunc():void
{
Alert.show("Invoke Ok");
}
public function getValue():Number
{
return 84;
}
protected function application1_creationCompleteHandler(event:FlexEvent):void
{
ExternalInterface.addCallback( "myFlexFunction" ,myFunc);
ExternalInterface.addCallback( "getValue" ,getValue);
}
]]>
</fx:Script>
<fx:Declarations>
<!-- 将非可视元素(例如服务、值对象)放在此处 -->
</fx:Declarations>
<mx:Button id="Test" label="Hello" click="text_clickHandler(event)">
</mx:Button>
</s:Application>
//HTML代码,Flex自动生成的代码中小改动。
<body>
<!-- SWFObject's dynamic embed method replaces this alternative HTML content with Flash content when enough
JavaScript and Flash plug-in support is available. The div is initially hidden so that it doesn't show
when JavaScript is disabled.
-->
<div id="flashContent">
<p>
To view this page ensure that Adobe Flash Player version
11.1.0 or greater is installed.
</p>
</div>
<noscript>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100px" height="100px" id="SampleApp">
<param name="movie" value="SampleApp.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="allowScriptAccess" value="sameDomain" />
<param name="allowFullScreen" value="true" />
<!--[if !IE]>-->
<object type="application/x-shockwave-flash" data="SampleApp.swf" width="100px" height="100px">
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="allowScriptAccess" value="sameDomain" />
<!--<![endif]-->
<!--[if gte IE 6]>-->
<p>
Either scripts and active content are not permitted to run or Adobe Flash Player version
11.1.0 or greater is not installed.
</p>
<!--<![endif]-->
<a href="http://www.adobe.com/go/getflashplayer">
<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash Player" />
</a>
<!--[if !IE]>-->
</object>
<!--<![endif]-->
</object>
</noscript>
<input type="button" value="test" οnclick="TestFlex()"/>
</body>
<script type="text/javascript">
function TestFlex()
{
var obj=document.getElementById('SampleApp');
//obj.myFlexFunction();
var vals=obj.getValue();
alert(vals);
}
</script>