JS与AS通信(ExternalInterface类)

object只能在IE中显示,最好不要用

embed,在IE和Chrome中都可良好显示

一、AS调用JS的方法,ExternalInterface类的call方法

ExternalInterface.call(functionName:String,...arguments)

fuctionName:要调用的JavaScript函数名

arguments:参数,可选

JS:

function haha(str){ return "js return:"+str; }

AS:

var aaa:String=ExternalInterface.call("haha","123");

mx.controls.Alert.show(aaa);


二、JS调用AS的方法,ExternalInterface类的addCallback方法

ExternalInterface.addCallback( functionName:String, closure:Function):void 

functionName:要注册的函数名

closure:对应的执行函数

AS:

protected function init():void { ExternalInterface.addCallback("diaoAS",diaoAS); }

public function diaoAS(message:String):void { Alert.show(message); }

JS:

function diaoAS() { this.swfID.diaoAS("来自JS"); }


完整的例子:

JS:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>AS和JS通信</title>

    <script type="text/javascript">

  function diaoJS(str)//被AS调用的函数

  {

   return str;

  }

 

  function diaoAS()

  {

   this.loadingSWF.diaoAS("来自JS");//正在调用AS函数

  }

    </script>

</head>

<body>

 <div style="height:200px">

  <embed id='loadingSWF' src='ha.swf' style='z-index:500; position:absolute;' width='100%' height='200px' bgcolor='#FFFFFF' wmode='transparent' quality='high'>

  </embed>

 </div>

 <div style="height:200px">

  <input type="button" value="点击调用AS" οnclick="diaoAS()"/>

 </div>

</body>

</html>


AS:

<?xml version="1.0" encoding="utf-8"?>

<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" minWidth="955" minHeight="600" creationComplete="init()">

 <fx:Script>

  <![CDATA[

   import mx.controls.Alert;

   

   protected function init():void

   {

    ExternalInterface.addCallback("diaoAS",diaoAS); //注册函数,方便被JS调用

   }

   public function diaoAS(message:String):void

   {

    Alert.show(message);

   }

   

   protected function fnJS():void

   {

    var strResult:String= ExternalInterface.call("diaoJS",myTxt.text); //正在调用JS函数

    Alert.show(strResult);

   }

  ]]>

 </fx:Script>

 <s:TextInput id="myTxt" left="10" top="10" width="194" height="68" fontSize="36" text="AS调用JS"/>

 <s:Button left="10" top="100" label="OK" width="194" height="78" fontSize="36" click="fnJS()"/>

</s:Application>


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值