現在談到AS3與PHP的互動,第一反應都會想到AMF
其實AMF也不過是利用PHP或者其他語言來寫的一個資訊後台罷了,
迴歸到原始,無非通訊還是這幾種方法。
(1)直接讀取
php:
<?
$state="開始接收";
$var1="收到";
echo "state=".$state."&var1=".$var1;
?>
as:
//btn是個按鈕 txt是動態文本,在flash裡面直接建立就OK
btn.addEventListener(MouseEvent.CLICK,loadMss);
txt.text="loading...";
function loadMss(e:MouseEvent):void
{
var urlLoader:URLLoader=new URLLoader();
mssLoader.dataFormat=URLLoaderDataFormat.VARIABLES;
mssLoader.load(new URLRequest("http://localhost/as3/admin.php"));//這裡就是php檔案的地址
mssLoader.addEventListener(Event.COMPLETE,completeFun);
}
function completeFun(e:Event):void
{
var loadData:URLVariables=URLVariables((e.currentTarget as URLLoader).data);
txt.text="正在:"+loadData.state+"\n";
txt.text+="接收情況:"+loadData.var1;
}
(2)讀取PHP產生的xml
php:
<?
//這裡只是簡單的echo出來了
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
echo "<pics>";
echo "<p1>1.jpg</p1>";
echo "<p2>2.jpg</p2>";
echo "</pics>";
?>
as:
//btn是個按鈕 txt是動態文本,在flash裡面直接建立就OK
btn.addEventListener(MouseEvent.CLICK,loadMss);
function loadMss(e:MouseEvent):void
{
var urlLoader:URLLoader=new URLLoader();
xmlLoader.load(new URLRequest("http://localhost/as3/xml.php"));//這裡就是php檔案的地址
xmlLoader.addEventListener(Event.COMPLETE,completeFun);
}
function completeFun(e:Event):void
{
var loadData:XML=XML((e.currentTarget as URLLoader).data);
txt.text=loadData.toString();
}
(3)通過GET傳出參數
//btn是個按鈕 txt是動態文本,在flash裡面直接建立就OK
System.useCodePage=true;
btn.addEventListener(MouseEvent.CLICK,loadMss);
function loadMss(e:MouseEvent):void
{
var getLoader:URLLoader=new URLLoader();
var request:URLRequest=new URLRequest();
request.url="http://enatool.com/something.php";//這裡是接收參數的地址
request.method=URLRequestMethod.GET;//傳出方法
request.data="s=1";//傳出具體的資訊
getLoader.load(request);
getLoader.addEventListener(Event.COMPLETE,completeFun);
}
function completeFun(e:Event):void
{
txt.text=(e.currentTarget as URLLoader).data;
}
(4)通過POST傳參
//btn是個按鈕 txt是動態文本,在flash裡面直接建立就OK
System.useCodePage=true;
btn.addEventListener(MouseEvent.CLICK,loadMss);
function loadMss(e:MouseEvent):void
{
var postLoader:URLLoader=new URLLoader();
var request:URLRequest=new URLRequest();
var vars:URLVariables=new URLVariables();
vars.s1="flash";
vars.s2="flex";
request.url="http://enatool.com/something.php";
request.method=URLRequestMethod.POST;
request.data=vars;//這裡的data可以是一個Object,或者Array
postLoader.load(request);
postLoader.addEventListener(Event.COMPLETE,completeFun);
}
function completeFun(e:Event):void
{
txt.text=(e.currentTarget as URLLoader).data;
}
和php或者類似asp,.net的資訊互動都是這樣。所以說不要把互動看的那麼難。
(如果要轉載請註明出處http://blog.sina.com.cn/jooi,謝謝)