从javascript / jquery调用AS函数

时间:2010-12-24 20:58:10

标签: javascript jquery actionscript-3 jquery-selectors mxml

使用jquery,我们可以在flex代码中调用一个函数。比如我有一个调用AS代码的按钮。如果可以的话,这样做怎么办?

 <script>
   function callas()
   {
    addBody();//call flex function        
   }
 </script>

 <input type="button" onclick="callas();" />

FLEX代码

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">


<mx:Script>
<![CDATA[

import mx.controls.Button;
import mx.controls.Alert;
import flash.display.InteractiveObject;
import flash.display.Sprite;
import flash.media.*;
import flash.net.*;


public function addBody():void
{

  Alert.show("Got input from JS");

}
</mx:Script>


</mx:Application >

2 个答案:

答案 0 :(得分:1)

它应该是这样的:

的Javascript

function getFlashMovie(movieName) {
    document.getElementById(movieName).setAttribute("name", movieName);
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    return (isIE) ? window[movieName] : document[movieName];
}

function callas()
{
   // You need to know the ID of the object/embed tag; swfobject has an attribute for that. see http://code.google.com/p/swfobject/wiki/documentation#How_can_you_configure_your_Flash_content?
   var swfobjectID = 'myFlashObjectID'  
   //call flex function 
   getFlashMovie(swfobjectID).addBody();
}

Actionscript / flex

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

<mx:Script>
<![CDATA[

import mx.controls.Button;
import mx.controls.Alert;
import flash.display.InteractiveObject;
import flash.display.Sprite;
import flash.media.*;
import flash.net.*;
import flash.external.ExternalInterface;

//                "javascript function", flash function
ExternalInterface.addCallback("addBody", addBody);

public function addBody():void
{
  Alert.show("Got input from JS");
}
</mx:Script>

</mx:Application >

<强>来源:
http://kb2.adobe.com/cps/156/tn_15683.html
http://code.google.com/p/swfobject/wiki/documentation#How_can_you_configure_your_Flash_content

答案 1 :(得分:0)

您需要使用名为ExternalInterface的Actionscript类与Javascript进行交互。

所以,如果你想从Flex或Flash调用Javascript函数,那么你应该使用这样的东西:

ExternalInterface.call("Javscriptfunction", parameters);

如果您想从Javascript调用Actionscript,请尝试以下操作:

ExternalInterface.addCallback("javascriptfunc", flexfunc);

protected function flexfunc(result:String):void{
    trace(result);
}