Flex与JavaScript的交互

一、在JavaScript中调用Flex方法
在Flex中可以用ExternalInterface来调用Flex的方法,途径是
1.通过在Flex应用可调用方法列表中添加指定的公用方法。在Flex应用中通过调用addCallback()可以把一个方法添加到此列表中。addCallback将一个ActionScript的方法注册为一个JavaScript和VBScript可以调用的方法。
addCallback()函数的定义如下:
addCallback(function_name:String, closure:Function):void
function_name参数就是在Html页面中脚本调用的方法名。closure参数是要调用的本地方法,这个参数可以是一个方法也可以是对象实例。

举个例子:
<mx:Script>
    import flash.external.*;
    public function myFunc():Number {
        return 42;
    }
    public function initApp():void {
        ExternalInterface.addCallback("myFlexFunction",myFunc);
    }
</mx:Script>

2.那么在Html页面中,先获得SWF对象的引用,也就是用<object .../>声明的Swf的Id属性,比如说是MyFlexApp。然后就可以用以下方式调用Flex中的方法。
<SCRIPT language='JavaScript' charset='utf-8'>
    function callApp() {
        var x = MyFlexApp.myFlexFunction();
        alert(x);
    }
</SCRIPT>
<button onclick="callApp()">Call App</button>



二、在Flex中调用 JavaScript
你 可以调用Html页面中的JavaScript,通过与JavaScript的交互,可以改变Style,调用远程方法。还可以将数据传递给Html页 面,处理后再返回给Flex,完成这样的功能主要有两种方法:ExternalInterface()和navigateToUrl()。
在Flex中调用JavaScript最简单的方法是使用ExternalInterface(),可以使用此API调用任意JavaScript,传递参数,获得返回值,如果调用失败,Flex抛出一个异常。
ExternalInterface封装了对浏览器支持的检查,可以用available属性来查看。
ExternalInterface的使用非常简单,语法如下:
flash.external.ExternalInterface.call(function_name: String[, arg1, ...]):Object;
参数function_name是要调用的JavaScript的函数名,后面的参数是JavaScript需要的参数。
举个例子说明如何调用JavaScript函数
Flex应用中,添加如下方法:
<mx:Script>
<?xml version="1.0" encoding="iso-8859-1"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Script>
        import flash.external.*;
   
        public function callWrapper():void {
            var f:String = "changeDocumentTitle";
            var m:String = ExternalInterface.call(f,"New Title");
            trace(m); 
        }
    </mx:Script>
    <mx:Button label="Change Document Title" click="callWrapper()"/>
</mx:Application>
Html页面中有如下函数定义:
<SCRIPT LANGUAGE="JavaScript">
    function changeDocumentTitle(a) {
        window.document.title=a;
        return "successful";
    }
</SCRIPT>

 

 

 

-------------------------------------------------------

评论:该方法是对滴,但在实际应用中好像有点问题,后来我使用了之官网提供的一段代码

 

以下示例演示了在 Flash Player 与 HTML 容器之间发送数据的过程。

package {
    import flash.display.Sprite;
    import flash.events.*;
    import flash.external.ExternalInterface;
    import flash.text.TextField;
    import flash.utils.Timer;
    import flash.text.TextFieldType;
    import flash.text.TextFieldAutoSize;

    public class ExternalInterfaceExample extends Sprite {
        private var input:TextField;
        private var output:TextField;
        private var sendBtn:Sprite;

        public function ExternalInterfaceExample() {
            input = new TextField();
            input.type = TextFieldType.INPUT;
            input.background = true;
            input.border = true;
            input.width = 350;
            input.height = 18;
            addChild(input);

            sendBtn = new Sprite();
            sendBtn.mouseEnabled = true;
            sendBtn.x = input.width + 10;
            sendBtn.graphics.beginFill(0xCCCCCC);
            sendBtn.graphics.drawRoundRect(0, 0, 80, 18, 10, 10);
            sendBtn.graphics.endFill();
            sendBtn.addEventListener(MouseEvent.CLICK, clickHandler);
            addChild(sendBtn);

            output = new TextField();
            output.y = 25;
            output.width = 450;
            output.height = 325;
            output.multiline = true;
            output.wordWrap = true;
            output.border = true;
            output.text = "Initializing.../n";
            addChild(output);

            if (ExternalInterface.available) {
                try {
                    output.appendText("Adding callback.../n");
                    ExternalInterface.addCallback("sendToActionScript", receivedFromJavaScript);
                    if (checkJavaScriptReady()) {
                        output.appendText("JavaScript is ready./n");
                    } else {
                        output.appendText("JavaScript is not ready, creating timer./n");
                        var readyTimer:Timer = new Timer(100, 0);
                        readyTimer.addEventListener(TimerEvent.TIMER, timerHandler);
                        readyTimer.start();
                    }
                } catch (error:SecurityError) {
                    output.appendText("A SecurityError occurred: " + error.message + "/n");
                } catch (error:Error) {
                    output.appendText("An Error occurred: " + error.message + "/n");
                }
            } else {
                output.appendText("External interface is not available for this container.");
            }
        }
        private function receivedFromJavaScript(value:String):void {
            output.appendText("JavaScript says: " + value + "/n");
        }
        private function checkJavaScriptReady():Boolean {
            var isReady:Boolean = ExternalInterface.call("isReady");
            return isReady;
        }
        private function timerHandler(event:TimerEvent):void {
            output.appendText("Checking JavaScript status.../n");
            var isReady:Boolean = checkJavaScriptReady();
            if (isReady) {
                output.appendText("JavaScript is ready./n");
                Timer(event.target).stop();
            }
        }
        private function clickHandler(event:MouseEvent):void {
            if (ExternalInterface.available) {
                ExternalInterface.call("sendToJavaScript", input.text);
            }
        }
    }
}
为了测试前面的 ActionScript 代码,请使用以下 HTML 模板嵌入生成的 SWF 文件:
<!-- saved from url=(0014)about:internet -->
 <html lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>ExternalInterfaceExample</title>
 <script language="JavaScript">
     var jsReady = false;
     function isReady() {
         return jsReady;
     }
     function pageInit() {
         jsReady = true;
         document.forms["form1"].output.value += "/n" + "JavaScript is ready./n";
     }
     function thisMovie(movieName) {
         if (navigator.appName.indexOf("Microsoft") != -1) {
             return window[movieName];
         } else {
             return document[movieName];
         }
     }
     function sendToActionScript(value) {
         thisMovie("ExternalInterfaceExample").sendToActionScript(value);
     }
     function sendToJavaScript(value) {
         document.forms["form1"].output.value += "ActionScript says: " + value + "/n";
     }
 </script>
 </head>
 <body onload="pageInit();">
 
     <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
             id="ExternalInterfaceExample" width="500" height="375"
             codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">
         <param name="movie" value="ExternalInterfaceExample.swf" />
         <param name="quality" value="high" />
         <param name="bgcolor" value="#869ca7" />
         <param name="allowScriptAccess" value="sameDomain" />
         <embed src="ExternalInterfaceExample.swf" quality="high" bgcolor="#869ca7"
             width="500" height="375" name="ExternalInterfaceExample" align="middle"
             play="true" loop="false" quality="high" allowScriptAccess="sameDomain"
             type="application/x-shockwave-flash"
             pluginspage="http://www.macromedia.com/go/getflashplayer">
         </embed>
     </object>
 
     <form name="form1" onsubmit="return false;">
         <input type="text" name="input" value="" />
         <input type="button" value="Send" onclick="sendToActionScript(this.form.input.value);" /><br />
         <textarea cols="60" rows="20" name="output" readonly="true">Initializing...</textarea>
     </form>
 
 </body>
 </html>

 

你可能感兴趣的:(JavaScript,function,Flex,input,import,actionscript)