JSON (JavaScript Object Notation),一种XML的减肥方法,用于在网络两端完成对象的序列化和反序列化过程。
JSON的实现比较多,包括有C, C++, C#, Java, JavaScript, Perl, Python等。JSON下载地址为:
http://www.JSON.org
这里选择的是客户端JAVASCRIPT和服务器端PHP的JSON实现(JSON.php,v 1.16)
使用JSON的客户端JAVASCRIPT脚本
1,包含JSON脚本
<script type="text/javascript" src="json.js"></script>
2,使用JSON解码(parse)
var sJSON = "{/"availableColors/" : [ /"red/", /"white/", /"blue/" ],/"availableDoors/" : [ 2, 4 ]}"
var oCarInfo = JSON.parse(sJSON);
alert(oCarInfo.availableColors[0]); //outputs "red"
alert(oCarInfo.availableDoors[1]); //ouputs "4"
3,使用JSON编码(stringify)
var oCar = new Object();
oCar.doors = 4;
oCar.color = "blue";
oCar.year = 1995;
oCar.drivers = new Array("Penny", "Dan", "Kris");
alert(JSON.stringify(oCar));
4, 使用zXML中的XMLHTTP发送
var oXmlHttp = zXmlHttp.createRequest();
oXmlHttp.open("post", "UpdateSudokuData.php", true);
//oXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oXmlHttp.onreadystatechange = function ()
{
if (oXmlHttp.readyState == 4)
{
if (oXmlHttp.status == 200)
{
alert(oXmlHttp.responseText);
}
else
{
alert("An error occurred: " + oXmlHttp.statusText);
}
}
};
oXmlHttp.send(JSON.stringify(oStatus));
使用JSON的服务端PHP脚本
1,使用JSON的PHP脚本
require_once("JSON.php");
2,使用JSON解码(decode)
$oJSON = new JSON();
$sJSONText = " {/"age/":26,/"hairColor/":/"brown/",/"name/":/"Mike/",/"siblingNames/":[/"Matt/",/"Tammy/"]}";
$oPerson = $oJSON->decode($sJSONText);
print("<h3>Person Information</h3>");
print("<p>Name: ".$oPerson->name."<br />");
print("Age: ".$oPerson->age."<br />");
print("Hair Color: ".$oPerson->hairColor."<br />");
print("Sibling Names:</p><ul>");
for ($i=0; $i < count($oPerson->siblingNames); $i++)
{
print("<li>".$oPerson->siblingNames[$i]."</li>");
}
print("</ul>");
3,使用JSON编码(encode)
class Person
{
var $age;
var $hairColor;
var $name;
var $siblingNames;
function Person($name, $age, $hairColor)
{
$this->name = $name;
$this->age = $age;
$this->hairColor = $hairColor;
$this->siblingNames = array();
}
}
$oJSON = new JSON();
$oPerson = new Person("Mike", 26, "brown");
$oPerson->siblingNames[0] = "Matt";
$oPerson->siblingNames[1] = "Tammy";
$sOutput = $oJSON->encode($oPerson);
print($sOutput);
4, 使用XMLHTTP接收
// 如果通过HTTP接收,则需要使用HTTP_RAW_POST_DATA方式,相应的发送方也不要设置发送的Content-Type
$oJSON = new JSON();
$oStatus = $oJSON->decode($HTTP_RAW_POST_DATA);
$sStatus = "id=".$oStatus->sId." row=".$oStatus->row." col=".$oStatus->col." value=".$oStatus->value;
echo $sStatus;