Ajax中使用JSON

來源:互聯網
上載者:User
ajax|js   提交資料使用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不行,源檔案參見書籍原始碼第三章



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.