AS3.0和php數據交互POST方式
AS3.0和php數據交互POST方式
首先打開flash建立一個as3.0的文件
拖 textarea和button組建到舞台上
分別給兩個組件命名:txtcontent和addcontent
然后點第一幀添加動作:
var url:String = “http://localhost/tt.php”; //執行操作數據庫的php文件
var requestData:URLRequest = new URLRequest(url); //新建URLRequest對象,用來獲取flash中textArea的數據
var loader:URLLoader = new URLLoader(); //建立URLLoader對象,用來發送flash中textArea的數據
addcontent.addEventListener(MouseEvent.CLICK,addData); //為button附事件對象,點擊按鈕執行addData函數
function addData(e:Event){
requestData.data = String; // .data 為URLRequest一個屬性分三種大家可以查手冊查到
requestData.method = URLRequestMethod.POST; //.method 也為 URLLoader的一個屬性值
var urlvariables:URLVariables = new URLVariables(); //建立URLVariables對象,
urlvariables.cc = txtcontent.text; //通過cc參數傳遞 txtcontent里的數據
requestData.data = urlvariables;//講urlvariables的數據賦值給.data
loader.load(requestData); //開始發送數據
}
php文件很簡單
<?
$content = $_POST["cc"]; //獲取flash傳遞過來的參數
$conn = mysql_connect(“localhost”,”root”,”123456″) or die(“mysql:”.mysql_error());
mysql_select_db(“guestbook”,$conn) or die(“mysql:”.mysql_error());
$sql = “insert into topic(content) values(‘$content’)”;
mysql_query($sql);
//以上為連接數據庫並執行sql語句
?>
我的代碼:
function sendPostJSON(array:Array):void {
var variables:URLVariables = new URLVariables(); //建立URLVariables對象
variables.name = 'HCity首都';
variables.age = '25';
/*
* 如果使用json數據的方式
var objectArray:String = '{"name":"didi","age":"28"}';
var json = JSON.decode(objectArray);
variables.name = json.name;
variables.age = json.age;
*/
var requert:URLRequest = new URLRequest('http://thinkphp3.com/addinfo.php');
requert.method = URLRequestMethod.POST;
requert.data = variables;
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onURLLoaderCompleteEvent);
loader.load(requert);
}
private function onURLLoaderCompleteEvent(event:Event):void {
var data:String = URLLoader(event.target).data;
trace('onURLLoaderCompleteEvent ok:'+data);
}
php服務端的代碼非常簡單,就是把接收到的post數據提交數據庫!