在AS2中通常使用LoadVars類與Web伺服器交換資料:
var msg:LoadVars = new LoadVars();
var msgSent:LoadVars = new LoadVars();
msg.var1 = "one";
msg.var2 = "two";
msgSent.onLoad = function(success:Boolean):Void {
if (success) {
trace("Message sent.");
}
else {
trace("Message failed.");
}
};
msg.sendAndLoad ("http://127.0.0.1:8080/communicate_flash/index.jsp", msgSent);
==================================================================== ===============
在 AS3 中,等同於:
var scriptRequest:URLRequest = new URLRequest ("http://127.0.0.1:8080/communicate_flash/index.jsp");
var scriptLoader:URLLoader = new URLLoader();
var scriptVars:URLVariables = new URLVariables();
scriptLoader.addEventListener(Event.COMPLETE, handleLoadSuccessful);
scriptLoader.addEventListener(IOErrorEvent.IO_ERROR, handleLoadError);
scriptVars.var1 = "one";
scriptVars.var2 = "two";
scriptRequest.method = URLRequestMethod.POST;
scriptRequest.data = scriptVars;
scriptLoader.load(scriptRequest);
function handleLoadSuccessful(evt:Event):void {
trace("Message sent.");
trace("DataReceived:" + evt.target.data);
}
function handleLoadError(evt:IOErrorEvent):void {
trace("Message failed.");
}
==================================================================== ===============
scriptLoader.load(scriptRequest): 實際上就是向伺服器發送了這樣一個請 求:
http://127.0.0.1:8080/communicate_flash/index.jsp? var1=one&var2=two
==================================================================== ===============
其中 communicate_flash/index.jsp 是我們在 Tomcat 中 webapps 下部署的 一個 web 應用程式:
index.jsp 檔案如下:
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
System.out.println("----- connected -----");
// 在和 flash 通訊時,請保證字元集為 UTF-8,否則傳輸中文會產生亂 碼
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
out.print("result1=天天"+request.getParameter ("var1")+",");
out.print("result2=快樂"+request.getParameter ("var2"));
%>
==================================================================== ===============
收到jsp頁面返回的資料後,會調用handleLoadSuccessful()函數:通過 evt.target.data得到資料:
result1=天天one,result2=快樂two
==================================================================== ===============
最後別忘了 jsp 就是servlet,因此能和 jsp 通訊也就能和 servlet 通訊。 當然與 php, asp 通訊方法也都是這樣的。以上就是flash與後台通訊最簡單、最 直接的方法。