DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解 >> Ajax中使用JSON
Ajax中使用JSON
編輯:AJAX詳解     
 提交數據使用JSon代替XML

    頁面:JSonExample.JSP

<%@ page contentType="text/Html; charset=GBK" %>
<Html>
<head>
<title>
JSON示例
</title>
<script type="text/Javascript" src="zXML.src.JS"></script>
<script type="text/Javascript" src="json.JS"></script>
<script type="text/Javascript">
 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;
        }
</script>
</head>
<body>
<br /><br />
<form action="#">
  <input type="button" value="發送JSON數據" />
</form>
<h2>
  服務器響應:
</h2>
<div id="serverResponse">
</div>
</body>
</Html>

    服務器:JSONExample.Java

package AJaxbook.chap4;

import Java.io.*;
import Java.Net.*;
import Java.text.ParseException;
import Javax.servlet.*;
import Javax.servlet.http.*;
import org.json.JSONObject;

public class JSONExample
    extends HttpServlet {
  //處理Post方法
  protected void doPost(HttpServletRequest request,
                        HttpServletResponse response) throws ServletException,
      IOException {
    String json = readJSONStringFromRequestBody(request);

    //使用JSON綁字AJax對象
    JSONObject JSonObject = null;
    try {
      jsonObject = new JSONObject(JSon);
    }
    catch (ParseException pe) {
      System.out.println("ParseException: " + pe.toString());
    }

    //返回輸出結果
    String responseText = "You have a " + JSonObject.getInt("year") + " "
        + jsonObject.getString("make") + " " + JSonObject.getString("model")
        + " " + " that is " + JSonObject.getString("color") + " in color.";

    response.setContentType("text/XML");
    response.getWriter().print(responseText);
  }

  //得到參數
  private String readJSONStringFromRequestBody(HttpServletRequest request) {
    StringBuffer JSon = new StringBuffer();
    String line = null;
    try {
      BufferedReader reader = request.getReader();
      while ( (line = reader.readLine()) != null) {
        JSon.append(line);
      }
    }
    catch (Exception e) {
      System.out.println("Error reading JSON string: " + e.toString());
    }
    return JSon.toString();
  }
}

注意:要引入json.js和json的源文件,使用JSon.jar不行,源文件參見書籍源代碼第三章

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved