示例
var xmlHttp;
//创建对象function createXMLHttpRequest(){
xmlHttp = zXmlHttp.createRequest();
}
function doJSON(){
//得到Car对象var car = getCarObject();
//用JSON字符串化car对象var carAsJSON = car.toJSONString();
alert("汽车对象JSON化为:\n" + carAsJSON);
var url = "JSONExample?timeStamp=" + new Date().getTime();
//创建对象createXMLHttpRequest();
xmlHttp.open("POST",url,true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader("Content-Type","application/x-www-form.urlencoded");
xmlHttp.send(carAsJSON);
}
//回调方法function handleStateChange(){
if (xmlHttp.readyState == 4){
if (xmlHttp.status == 200){
parseResults();
}
}
}
//解析结果function parseResults(){
var responseDiv = document.getElementById("serverResponse");
if (responseDiv.hasChildNodes()){
responseDiv.removeChild(responseDiv.childNode[0]);
}
var responseText = document.createTextNode(xmlHttp.responseText);
responseDiv.appendChild(responseText);
}
//得到Car对象function getCarObject(){
return new Car("Dodge","Coronet R/T",1968,"yellow");
}
//Car构造函数function Car(make,model,year,color){
this.make = make;
this.model = model;
this.year = year;
this.color = color;
}
服务器响应: