1.flex端 Json encode/decode 数据
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute"
<mx:Script>
<![CDATA[
import mx.events.DataGridEvent;
import mx.controls.TextInput;
import mx.rpc.events.ResultEvent;
import mx.collections.ArrayCollection;
import com.adobe.serialization.json.JSON;
[Bindable]
private var dataArray:ArrayCollection;
private function initDataGrid():void
{
dataArray = new ArrayCollection();
getData.send();
}
private function getPHPData(event:ResultEvent):void
{
var rawArray:Array;
var rawData:String = String(event.result);
rawArray = JSON.decode(rawData) as Array;
dataArray = new ArrayCollection(rawArray);
}
private function sendPHPData():void
{
var objSend:Object = new Object();
var dataString:String =
JSON.encode(dataArray.toArray());
//dataString = escape(dataString);
objSend.setTutorials = "true";
objSend.jsonSendData = dataString;
sendData.send(objSend);
}
]]>
</mx:Script>
<mx:HTTPService
url="../getdata.php"
useProxy="false" method="GET"
resultFormat="text" >
</mx:HTTPService>
<mx:HTTPService
url="../senddata.php"
useProxy="false" method="GET"
</mx:HTTPService>
2.php端 Json encode/decode 数据
/*getdata.php*/
<?php
$returnArray = array();
$query = 'SELECT * FROM table';
$result = mysql_query($query);
while($rs = mysql_fetch_object($result))
{
array_push($returnArray, $rs);
}
echo json_encode($returnArray);
?>
/*senddata.php*/
<?php
$jsonString = urldecode($_GET['jsonSendData']);
$jsonString = str_replace("\", "", $jsonString);
$data = json_decode($jsonString, true);
foreach ($data as $dataEntry) {
//add data to database
}
?>
3.问题
1)写入后台的数据有时是空数据
原因:在Flex端,dataString中存放的数据要确保转换成 String类型。
2)中文字符乱码
Json只支持Utf-8的字符类型,要确保从Flex端,MySQL端传入的数据都是Utf-8的字符类型;
特别要注意:在Flex的 sendPHPData() 中要注释掉dataString = escape(dataString)这句代码(网上很多例子都是没注释掉,我按照网上对中文乱码的处理方式,都行不通,最后才发现了这个问题)。
希望对大家有所帮助。