FLASH AS3與網頁JS參數值傳遞的問題
2020-07-17 13:17:19
供稿:網友
讓我們一干人等郁悶了1個多小時的一個問題,結果才發現,JS處理JSON結構的時候,如果JSON格式與所需的不符,則函數都不會執行。
問題起因:AS3調用PHP,PHP異步返回一個XML結構,AS3取XML結構中的某些節點值賦給某個對象,然后通過與JS交互將值傳遞給JS。
調試過程:
PS item為PHP返回的xml:
varobj_info:Object=newObject();
obj_info["from"]=item..from;
obj_info["context"]=item..text;
trace("UserMessage-->Messagefromservicechat::" obj_info);
trace("UserMessage-->Messagefromservicechatfrom::" obj_info["from"]);
trace("UserMessage-->Messagefromservicechatcontext::" obj_info["context"]);
this.dispatchEvent(newMessageEvent(MessageEvent.USERGETSUCCESS,obj_info));此處輸出:
UserMessage-->Messagefromservicechat::[objectObject]
UserMessage-->Messagefromservicechatfrom::[objectObject]
UserMessage-->Messagefromservicechatcontext::[objectObject]這個obj_info對象就是傳遞給JS的對象,而JS需要的JSON結構為: { "from" : "...", "context" : "..." } ,這兩個屬性值都為string類型。
發現錯誤點:JS內部調用函數時,在三種情況下調試:1、不傳參數給函數;2、傳一個正確類型和結構的JSON作為參數;3、傳一個不正確類型和結構的JSON作為參數。 經過這三次調試后發現,如果JSON結構不正確,則JS函數不會執行。 這樣一來,問題就轉到了Flash傳遞給JS的參數上。對比之前Flash的調試輸出的結果,確認Flash從PHP獲取到XML后,在給傳遞給JS參數賦值的時候需要強制轉換。
最后解決方法:修改賦值部分代碼:
varobj_info:Object=newObject();
obj_info["from"]=(item..from).toString();
obj_info["context"]=(item..text).toString();
trace("UserMessage-->Messagefromservicechat::" obj_info);
trace("UserMessage-->Messagefromservicechatfrom::" obj_info["from"]);
trace("UserMessage-->Messagefromservicechatcontext::" obj_info["context"]);
this.dispatchEvent(newMessageEvent(MessageEvent.USERGETSUCCESS,obj_info));