//jsp代码
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!-- //--> </script> <!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="script/jquery-1.7.2.min.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <script type="text/javascript"> $(function() { $(":text").change(function() { alert(1111); var url = "testServlet"; $.post(url, {"func" : "getNameAndTime"}, function(data) { alert(data.name); },"json"); }); }); </script> </head> <body> <input type="text"/> </body> </html>
testServlet
package com.javaweb; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; /** * Servlet implementation class TestServlet */ @WebServlet("/testServlet") public class TestServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public TestServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String str = request.getParameter("func"); System.out.println(str); // request.setAttribute("name", 8); Map<String, Object> result = new HashMap<String, Object>(); result.put("name", "name"); Gson gson = new Gson();//需导入gson.jar String jsonStr = gson.toJson(result); response.setContentType("text/javascript"); response.getWriter().print(jsonStr); } }