XML 結構清楚但冗長,若只是要傳遞一組簡單的物件屬性,JSON 往往更輕巧。以下範例把一輛車的資訊序列化成 JSON 字串後 POST 給伺服器,伺服器解析後再拼出回應。
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest(){
xmlHttp = zXMLHttp.createRequest();
}
function doJSON(){
var car = getCarObject();
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");
while (responseDiv.hasChildNodes()){
responseDiv.removeChild(responseDiv.childNodes[0]);
}
responseDiv.appendChild(
document.createTextNode(xmlHttp.responseText)
);
}
function getCarObject(){
return new Car("Dodge", "Coronet R/T", 1968, "yellow");
}
function Car(make, model, year, color){
this.make = make;
this.model = model;
this.year = year;
this.color = color;
}
</script>
頁面只需一顆觸發 doJSON() 的按鈕,以及一個 <div id="serverResponse"> 作為回應區。
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String json = readJSONStringFromRequestBody(request);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
} catch (Exception pe) {
System.out.println("Parse error: " + pe.toString());
return;
}
String responseText = "You have a " + jsonObject.getInt("year") + " "
+ jsonObject.getString("make") + " "
+ jsonObject.getString("model")
+ " that is " + jsonObject.getString("color") + " in color.";
response.setContentType("text/html; charset=UTF-8");
response.getWriter().print(responseText);
}
private String readJSONStringFromRequestBody(HttpServletRequest request) throws IOException {
StringBuffer json = new StringBuffer();
String line;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null){
json.append(line);
}
return json.toString();
}
伺服器端使用 org.json.JSONObject 把整段請求本文還原成物件,再以 getInt、getString 取值,比解析 XML 省下不少樣板程式。前端則靠 json.js 提供的 toJSONString() 完成序列化,因此頁面必須正確載入 json.js,光有 json.jar 並不足夠。
另外提醒:原範例把 Content-Type 設為 application/x-www-form-urlencoded,但實際傳送的是 JSON 本文。若想讓語意更明確,可改用 application/json,並在後端以 UTF-8 讀取,避免中文欄位出現亂碼。