js调用flex中as方法出错的解决办法

 需要在mxml文件中添加下面代码中的红色部分:
mxml完整源码如下:

<?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"   initialize="application1_initializeHandler(event)">
 <fx:Script>
  <![CDATA[
   import mx.controls.Alert;
   import mx.events.FlexEvent;
   import flash.system.Security;
   
   Security.allowDomain("*");
   Security.allowInsecureDomain("*");
   protected function application1_initializeHandler(event:FlexEvent):void
   {
    // TODO Auto-generated method stub
    if(ExternalInterface.available)
    {
     ExternalInterface.addCallback("getFlexMsg",getMsgFromFlex);
    }
   }
   public function getMsgFromFlex():void
   {
    btnOK.label="js调用flex成功";
   }
   protected function button1_clickHandler(event:MouseEvent):void
   {
    // TODO Auto-generated method stub
    var msg:String=ExternalInterface.call("jsFun");
    mx.controls.Alert.show(msg);
   }
  ]]>
 </fx:Script>
 <fx:Declarations>
  <!-- 将非可视元素(例如服务、值对象)放在此处 -->
 </fx:Declarations>
 <s:Button id="btnOK" x="268" y="103" width="137" label="按钮" click="button1_clickHandler(event)"/>
</s:Application>

JS调用代码如下:

function jsFun() //被flex中的as方法调用
  {
   return "来自js";
  }

  function getFlexMsg() //调用flex中的as方法
  {
   var msg=document.getElementById("JSandFlex").getFlexMsg(); //说明:JSandFlex是html文件中flash builder生成的swf对象的id,getFlexMsg是在flex中注册的可被js调用的as方法别名
  }

以上js代码可直接放在index.template.html的<head></head>内,也可放在单独的文件中然后在index.template.html中引用.

posted @ 2011-11-01 18:04  liancs  阅读(172)  评论(0编辑  收藏  举报