JSON 在Ajax数据交换中的简单运用

随着浏览器内核更新,原先的json.js在最新的谷歌浏览下不管用了,运行报错,特此修改下代码,不使用json.js,使用Object自带的json转换方法,修改时间,2016年10月26日.

首先需要创建一个Servlet类,命名为JSONTest.java. 然后配置下web.xml文件,我的是自动生成的,也就没改动.web.xml的内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>JSONTest</servlet-name>
    <servlet-class>servlet.ajax.JSONTest</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>JSONTest</servlet-name>
    <url-pattern>/servlet/JSONTest</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

接下来,就是创建JS文件了,命名为yulei.js,其中的url是访问上面的servlet的路劲.js内容如下:

function Car(make,model,year,color){      
    this.make=make;  
    this.model=model;  
    this.year=year;  
    this.color=color;  
}  


function sendRequest(){  
    var car=new Car('Dodge','Cornet R\T',2009,'yellow');  
 //   var pars="car="+car.toJSONString();  
      var pars="car="+Object.toJSON(car);
    var url="servlet/JSONTest";  
    var mailAjax= new Ajax.Request(  
           url,  
           {   
             method:'get',  
             parameters:pars,  
             onComplete:jsonResponse,  
             onException: function(x, e) { alert(e) }
           }  
        );  
}  
  
function jsonResponse(originalRequest){  
    alert(originalRequest.responseText);  
    var myObj=originalRequest.responseText.parseJSON();  
    alert(myObj.name);  
}  


然后,新建一个jsonTest.jsp文件,里面主要是加载一些js文件,和一个按钮,内容如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'jsonTest.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
      <script type="text/javascript" src="js/prototype.js"></script>  
<!--      <script type="text/javascript" src="js/json.js"></script>  
 -->      <script type="text/javascript" src="js/yulei.js"></script>  
  </head>
  
  <body>
        This is my JSP page. <br>  
       <input type="button" value="测试" onclick="sendRequest()"/>  
  </body>
</html>

 

最后,我们就编写Servlet类的内容:

package servlet.ajax;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

public class JSONTest extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
         
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		
		String s3=request.getParameter("car");
		System.out.println(s3);
		try {
			JSONObject jsonObject=new JSONObject(s3);
			System.out.println(jsonObject.getString("model"));
			System.out.println(jsonObject.getString("year"));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		JSONObject resultJSON=new JSONObject();
		try {
			resultJSON.append("name", "violet");
			resultJSON.append("occupation", "developer");
			resultJSON.append("age", new Integer(22));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		out.print(resultJSON.toString());
	}
}

这个Servlet的功能是:首先获取前台JS ajax请求传来的JSON数据,将其中的某些属性打印出来(你也可以Debug查看),然后重新新建一个JSON对象,并将其以字符串的形式传到前台,我们就可以获取到这个新建的JSON数据.

 

这就是简单的JSON在AJAX请求中数据传输的作用.

 

 


 

 

 

 

 

posted on 2013-11-15 10:32  吴一达  阅读(137)  评论(0编辑  收藏  举报

导航