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

这篇文章是从网络上摘的,感觉乱乱的,就整理了下。写的时候,也遇到了些问题,就是 prototype.js和json.js的冲突. 关于冲突,请参考我的另一个博文prototype.js 和json.js 冲突。

首先需要创建一个Servlet类,命名为JSONTest1.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>JSONTest1</servlet-name>
    <servlet-class>servlet.ajax.JSONTest1</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>JSONTest1</servlet-name>
    <url-pattern>/servlet/JSONTest1</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 url="servlet/JSONTest1";
    var mailAjax= new Ajax.Request(
		   url,
		   { 
			 method:'get',
			 parameters:pars,
			 onComplete:jsonResponse  //执行成功时,会调用这个函数.
		   }
		);
}

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="prototype.js"></script>
	  <script type="text/javascript" src="json.js"></script>
	  <script type="text/javascript" src="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 JSONTest1 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请求中数据传输的作用.

 

 


 

 

 

 

 

你可能感兴趣的:(json,Ajax)