Servlet+Jquery+Ajax案例

因为很多时候我们用到异步刷新,所以我们现在来做一个小的demo

package org.heinrich.servlet;

import java.io.IOException;

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


@WebServlet("/tojson.aa")
public class AjaxServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
    public AjaxServlet() {
        super();
        
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		 String json = "{name:'heinrich',age:'10'}";  
		 response.setContentType("text/html");
		 response.getWriter().write(json);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

下面是html代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.3.2.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ajax</title>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() { 
	
	$("#ajax").click(
		
	function(){
		alert("dddd");
		$.ajax({
			url: "${pageContext.request.contextPath}/tojson.aa",
			dataType:"json",
			success:function(data){
				alert("name="+data.name+",age="+data.age);
			},
			error:function(){
			alert("aaaa");	
			}
		});
	}
	);
	
	
	}); 

	
	
</script>
<table>
	<tr>
		<td>
			<input type="submit" value="TestAjax" id="ajax">
		</td>
	</tr>
</table>

</body>
</html>


你可能感兴趣的:(Servlet+Jquery+Ajax案例)