flex和javascript交互例子
flex 代码:flexjavascript.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" xmlns:supportClasses="com.esri.ags.skins.supportClasses.*" minWidth="200" minHeight="300" creationComplete="initApp()"><fx:Script><![CDATA[import mx.controls.Alert; public function flexHelloWorld(param1:String, param2:String):String { Alert.show("param1: " + param1 + "; param2:" + param2); return "Hello " + param1 + param2; } //初始化定义,可以被javascript调用的函数public function initApp():void { ExternalInterface.addCallback("flexHelloWorld", flexHelloWorld); } //调用javascript的hello函数,传递的参数是flex:quanjingpublic function jspHello():void { var s:String = ExternalInterface.call("hello", "Flex:quanjing"); Alert.show(s); } ]]></fx:Script><fx:Declarations><!-- 将非可视元素(例如服务、值对象)放在此处 --></fx:Declarations><mx:Button x="52" y="58" label="call javascript" click="jspHello()"/> </s:Application>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>test</title><script type="text/javascript" src="swfobject.js"></script><script language="JavaScript" type="text/javascript">//被flex调用的函数function hello(param) { alert(param); return "jsp Hello33333333:" + param; } //调用flex里的函数flexHelloWorld,传递两个参数hello,world。//在javascript里可以调用flex的函数,但必须在flex初始化时候指定过之后, function callFlexFunction() { var x = thisSWF("mySWF").flexHelloWorld("Hello", "world"); alert(x); }//根据id获取flex对象function thisSWF(swfID){if (navigator.appName.indexOf("Microsoft") != -1) {return window[swfID];} else {return document[swfID];}}swfobject.embedSWF("flexjavascript.swf"+window.location.search, "mySWF", "100%", "100%", "9.0.0");</script><style type="text/css" media="screen">html, body, #mySWF { height:400px; }body { margin:0; padding:0; overflow:hidden; }</style></head><body style="margin:0px;padding:0px;"><div id="mySWF"></div> <div> <input type=button value="Call Flex" onclick="callFlexFunction()"/> </div></body></html>