javascript向flash swf檔案傳遞參數值注意細節

來源:互聯網
上載者:User

問題:如何使用javascript向SWF檔案傳遞參數?
在網上找了一個完整的教程,很有啟發性和實用性,如下是完整實現的步驟:
配置SwfObject
Swfobject2是目前檢測使用者是否安裝Flash的最佳方法。它被認為是‘行業標準',並且Adobe所有產品的新版本(Flex4,Flash CS5)都會使用SwfObject來檢測Flash Player。
先要下載,解壓ZIP檔案,複製swfobject.js檔案到你的web伺服器上,根目錄下建立名為'js'根資料夾是個不錯的想法。(因此檔案位置應該是http://myserver.com/js/swfobject.js)。我們會在以後建立的HTML檔案中參考這個檔案的。如果你想使用ExpressInstall功能(為使用者提供簡單的升級方法),你必須將expressInstall.swf複製到相同的檔案夾下。
配置HTML檔案
HTML檔案包括兩個Javascript。一個用來抓取來自網址的參數。這是由Matt White建立的,它雖然簡單但十分有效。代碼如下: 複製代碼 代碼如下:<script type="text/javascript">
/* Get URL Parameter in Javascript. Code from: http://mattwhite.me/11tmr.nsf/D6Plinks/MWHE-695L9Z */
function getURLParam(strParamName){
var strReturn = "";
var strHref = window.location.href;
if ( strHref.indexOf("?") > -1 ){
var strQueryString = strHref.substr(strHref.indexOf("?"));
var aQueryString = strQueryString.split("&");
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
if ( aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
var aParam = aQueryString[iParam].split("=");
strReturn = aParam[1];
break;
}
}
}
return unescape(strReturn);
}
</script>

將如上代碼放置到你的HTML檔案的HEAD標籤中。你同樣需要將匯入SWFObject指令碼匯入進來,代碼如下:
<script type="text/javascript" src="/js/swfobject.js"></script>另一個Javascript是使用SwfObject插入SWF檔案。你可以將其放置在HTML檔案的任何地方。首先我們要做的是建立一個DIV標籤,在沒有安裝合適的Flash Player時提示使用者。 複製代碼 代碼如下:<div id="flashcontent">
<strong>This content requires Flash Player 9 (or a more recent version).
<noscript>Make sure JavaScript is turned on. </noscript>
You need to <a href="http://www.adobe.com/shockwave/download/index.cgi?p1_prod_version=shockwaveflash" target="_blank">
<span style="text-decoration: underline;">upgrade your Flash Player</span></a></strong>
</div>

在DIV標籤內你可以輸入任何想輸入的內容。添加圖片或者反饋資訊隨你喜歡,因為這些內容都會被SWF檔案所替換。
接下來是實現替換功能的Javascript: 複製代碼 代碼如下:<script type="text/javascript">
var flashvars = { test:getURLParam("test") };
var params = {};
var attributes = {};
swfobject.embedSWF("/articlefiles/jsvars/jsvars.swf", "flashcontent", "550", "400", "9.0.0","", flashvars, params, attributes);
</script>

注意第二行,我們調用了Javascript函數'getURLParam',這個函數已經被插入到HTML檔案中。我們所傳遞的名字正是希望從網址中捕獲的參數名。
建立Flash檔案
接下來該建立Flash檔案了。將一個文字框添加到舞台上。在屬性面板中設定為'動態文本',執行個體名為'mytextField'。通過點擊'顯示文本周圍邊框'實現在選中文字框時顯示邊框。
捕獲傳遞進來的參數需要使用如下的try/catch語句: 複製代碼 代碼如下:try {
var key:String; // This will contain the name of the parameter
var val:String; // This will contain the value of the parameter
var flashvars:Object = LoaderInfo(this.root.loaderInfo).parameters;
for (key in flashvars) {
val = String(flashvars[key]);
mytextField.text = key+": "+val;
}
} catch (error:Error) {
// what to do if an error occurs
}

檔案:jsvars_test.fla
將檔案和HTML檔案一併上傳到伺服器上。當運行檔案時,你會看到文字框中的'test:'字樣。
注意:如果SWF無法顯示,你只看到了'升級Flash Player'字樣,說明伺服器上缺少某些東西。確保你已經將SwfObject檔案(swfobject.js)上傳到了http://myserver.com/js/swfobject.js。同時確保HTML檔案中的SwfObject檔案和SWF檔案路徑正確。如果仍然有問題,查看一下例子的源檔案及路徑。
接下來,試著像這樣添加test參數http://www.flashmagazine.com/articlefiles/jsvars/jsvars_test.html?test=something.如果一切正常,你將會看到'test:something',表明你已經成功的將參數傳遞到Flash檔案中。
更進一步
你同樣可以設定來自SWF檔案的參數。在這個例子中http://www.flashmagazine.com/articlefiles/jsvars/jsvars.html?test=something&id=someID我們同樣實現了發送參數。
FLA檔案包含兩個分別命名為'variablesReceived'和'variablesToSend'的文字框,以及一個用來發送新參數的按鈕。這個例子的HTMl檔案被設定接收'test'和'id'兩個參數。首先我們為第一個文字框添加一些說明性文字:
variablesReceived.text ="Variables passed in:" + " ";接下來該接收變數了: 複製代碼 代碼如下:try {
var key:String;
var val:String;
var flashvars:Object = LoaderInfo(this.root.loaderInfo).parameters;
for (key in flashvars) {
val = String(flashvars[key]);
variablesReceived.appendText("\t" + key + ": " + val + " ");
}
} catch (error:Error) {
variablesReceived.appendText(error.toString());
}

這將會在第一個文字框中列舉出所有的flashvars。我們在這個檔案中使用到的另一個主要函數就是發送變數函數: 複製代碼 代碼如下:// Sending parameters
function sendVariables(e:MouseEvent):void {
// First we grab the URL of the HTML document and split it into an array
var htmlUrl:String = ExternalInterface.call("window.location.href.toString");
// split the string at the questionmark
var splitUrl:Array = htmlUrl.split("?");
// use only the first part (ditch existing parameters)
var trimmedUrl:String = splitUrl[0];
// get the parameters we want to append to the URL
var parameters:String = variablesToSend.text;
// combine url and parameters with a new questionmark
var requester:URLRequest = new URLRequest(trimmedUrl+"?"+parameters);
// reload the page
navigateToURL(requester, '_self');
}

這裡我們使用了一個小小技巧,通過使用'ExternalInterface.call'捕獲SWF檔案插入的HTML文本的網址。Flash檔案只知道指向自身的網址,這個技巧突破了這個限制。ExternalInterface在SwfObject預設情況下是被開啟的,但你可以手動關閉它。

我們不需要當前網址中的參數(也就是'…?test=something&id=5′)。因此我們只保留了問號之前的部分並將其儲存在'trimmedUrl'變數中以備將來之用。我們捕獲'variablesToSend'文字框中的參數,並將其傳遞到URLRequest中。通過將request傳遞給'navigateToURL',瀏覽器會重新載入HTML頁面並在'variablesReceived'文字框中顯示最近提交的值對。

注意:你不能在Flash中測試它。需要將檔案上傳到伺服器上,因為FlashVars和ExternalInterface都需要SWF被插入到瀏覽器中。

最後我們必須使用addEventListener為發送按鈕設定調用'sendVariables'方法。
sendButton.addEventListener(MouseEvent.CLICK,sendVariables);現在你已經知道如何使用Javascript相互傳遞參數了。讓我們用我們的所學做一些有用的事情。

建立選項組的導航
結束之前,讓我們構建一個小型菜單系統,這個系統可以高亮顯示當前的點擊按鈕,你可以下載已完成檔案或者運行案例,讓我們看一下代碼:
首先停止SWF的時間軸播放,為滑鼠點擊設定事件監聽器。
stop();
// setup our 5 buttons
item1.addEventListener(MouseEvent.CLICK, gotoURL);
item2.addEventListener(MouseEvent.CLICK, gotoURL);
item3.addEventListener(MouseEvent.CLICK, gotoURL);
item4.addEventListener(MouseEvent.CLICK, gotoURL);
item5.addEventListener(MouseEvent.CLICK, gotoURL);當仍然一個按鈕被點擊,他們都會執行'gotoURL'函數。接下來,我們捕獲來自網址的參數: 複製代碼 代碼如下:// grab variables
try {
var key:String;
var val:String;
var flashvars:Object = LoaderInfo(this.root.loaderInfo).parameters;
for (key in flashvars) {
val = String(flashvars[key]);
if(key == "item"){ // If the parameter is called 'item'...
if(val.substr(0,4) == "item"){ // ... and the name of the button starts with the characters 'item'...
// ... we can extract the number-part of the item-name and go to the correct frame
var frameToGoTo:Number = Number( val.substr(4,1) );
gotoAndStop( frameToGoTo+1 );
}
}
}
} catch (error:Error) {
// what to do if an error occurs
}

正如你所看到的,這和之前的做法十分相似。但這次我們傳遞的參數名字為'item'。這個參數是我們點擊的按鈕的名字。
接下來是gotoURL函數。 複製代碼 代碼如下:// Get the new page
function gotoURL(e:MouseEvent):void {
// First we grab the URL of the HTML document and split it into an array
var htmlUrl:String = ExternalInterface.call("window.location.href.toString");
// split the string at the questionmark
var splitUrl:Array = htmlUrl.split("?");
// use only the first part (ditch existing parameters)
var trimmedUrl:String = splitUrl[0];
// get the name of the button clicked and set it as a parameter
var parameters:String = "item="+e.currentTarget.name;
// combine url and parameters with a new questionmark
var requester:URLRequest = new URLRequest(trimmedUrl+"?"+parameters);
// reload the page
navigateToURL(requester, '_self');
}

我們通過聯合'item='字元以及點擊的按鈕名字建立自己的參數。然後將網址以及參數傳遞到navigateToURL方法中重新載入帶有新參數的HTML頁面。

事件是如何工作的:當一些東西被點擊時我們使用addEventListener()方法監聽點擊事件,事件包含被點擊的對象的引用。'currentTarget'屬性會引用被點擊的對象(e.currentTarget),這樣一來我們就可以使用e.currentTarget.name獲得其名字。

要成為一個完整的菜單系統,你還需要使載入新的網址,而不是像例子中使用相同的網址。你現在應該知道最基本的知識。它同時可以以多種方式運行。可以將網址當做變數儲存在SWF中,從一個XML檔案載入,或者更多其它的方式。因此我把這些交給你。如果你使用本教程建立瞭解決方案,請在評論中張貼網址,以便其他學習者可以看到它.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.