woaidongmao

文章均收录自他人博客,但不喜标题前加-[转贴],因其丑陋,见谅!~
随笔 - 1469, 文章 - 0, 评论 - 661, 引用 - 0
数据加载中……

Ajax中使用JSON

提交数据使用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数据" onclick="doJSON();"/>
</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.jsjson的源文件,使用json.jar不行,源文件参见书籍源代码第三章

参考:Ajax基础教程  作笔记吧 

 

posted on 2009-07-28 11:28 肥仔 阅读(644) 评论(0)  编辑 收藏 引用 所属分类: Web-前台


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理