PHP5有內建 JSON 的函式;PHP4沒有,但可以用 PEAR 的 JSON 類別。
AS3 則可以用 as3corelib 裡的 JSON 類別。
以下是將DB資料轉換成JSON的例子。
mysql2json4.php
/*** shinder.lin@gmail.com
for PHP4
*/
require_once("JSON.php");
function mysql2json4($sql) {
if(is_string($sql)) {
$query = mysql_query($query) or die(mysql_error());
} else {
$query = $sql;
}
$ar = array();
if($total = mysql_num_rows($query)) {
while($row = mysql_fetch_assoc($query)) {
$obj = array();
foreach($row as $key => $value) {
$obj[ $key ] = $value;
}
array_push($ar, $obj);
}
mysql_data_seek($query, 0);
}
$json = new Services_JSON();
return $json->encode($ar);
}
?>
test_mysql2json4.php
require("mysql2json4.php");
mysql_connect("localhost", "root", "");
mysql_select_db("test");
mysql_query("SET NAMES 'utf8'");
$q = mysql_query("select * from ctest");
echo mysql2json4($q);
?>
test_json.fla frame actions:
import com.adobe.serialization.json.*;
var ur:URLRequest = new URLRequest("http://localhost/json_test/test_mysql2json4.php");
var ul:URLLoader = new URLLoader();
ul.addEventListener(Event.COMPLETE, onComplete);
ul.load(ur);
function onComplete(evt:Event) {
trace(ul.data);
var o:Object = JSON.decode(ul.data);
QopDump.echo(o);
}
資料傳給 PHP
test_json_insert4.php
require_once("JSON.php");
$raw = $GLOBALS["HTTP_RAW_POST_DATA"];
$json = new Services_JSON();
$ar = (array) $json->decode($raw);
mysql_connect("localhost", "root", "");
mysql_select_db("test");
mysql_query("SET NAMES 'utf8'");
// watch out for sql injection
$sql = sprintf("INSERT INTO `ctest` (`sno`, `name`, `phone`) VALUES (NULL, '%s', '%s')", $ar['name'], $ar['phone']);
echo (bool) mysql_query($sql);
?>
test_json_submit.fla frame actions:
import com.adobe.serialization.json.*;
var ur:URLRequest = new URLRequest("http://localhost/json_test/test_json_insert4.php");
ur.method = URLRequestMethod.POST;
var ul:URLLoader = new URLLoader;
submit_btn.addEventListener(MouseEvent.CLICK, onSubmit);
function onSubmit(evt:MouseEvent):void {
var obj:Object = {name:name_ti.text, phone:phone_ti.text};
var str:String = JSON.encode(obj);
ur.data = str;
ur.contentType = "text/plain";
ul.load(ur);
// trace(str);
}
ul.addEventListener(Event.COMPLETE, onComplete);
function onComplete(evt:Event) {
info_ta.text = ul.data;
}
相關檔案下載
2 則留言:
QopDump.echo(o);
這句話在AS裡不解.也有出現Bug@.@
QopDump是什麼的物件,echo是php的語法
自訂的類別, 請參考這裡 http://qops.blogspot.com/2007/06/dump-as3.html
張貼留言