Jquery+ajax+json+servlet原理和Demo
大致过程: 用户时间点击,触发js,设置$.ajax,开始请求。服务器响应,获取ajax传递的值,然后处理。以JSON格式返回给ajax。ajax在sucess对应的函数中将返回的json数据进行解析,然后输出到jsp页面。
1.前台index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";%>Jquery Ajax Json Servlet Demo
返回数据:
2.后台Servlet
/* * $filename: JsonAjaxServlet.java,v $ * $Date: Sep 1, 2013 $ * Copyright (C) ZhengHaibo, Inc. All rights reserved. * This software is Made by Zhenghaibo. */package com.njupt.zhb.test;import java.io.IOException;import java.io.PrintWriter;import java.net.URLDecoder;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/* *@author: ZhengHaibo *web: http://blog.csdn.net/nuptboyzhb *mail: zhb931706659@126.com *Sep 1, 2013 Nanjing,njupt,China */public class JsonAjaxServlet extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); String userName = request.getParameter("userName"); userName=URLDecoder.decode(userName, "UTF-8"); String content = request.getParameter("content"); content=URLDecoder.decode(content, "UTF-8"); System.out.println("userName:"+userName); System.out.println("content:"+content); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); //将数据拼接成JSON格式 out.print("{\"yourName\":\"" + userName + "\",\"yourContent\":\""+content+"\"}"); out.flush(); out.close(); }}
3.配置文件web.xml
index.jsp jsonAjaxAction com.njupt.zhb.test.JsonAjaxServlet jsonAjaxAction /jsonAjaxAction
4.其他
1.需要导入jquery.min.js 2.注意乱码的解决方案: 2.1:js中对字符串进行编码,即:encodeURI(encodeURI(userNameObj)) 2.2:在Servlet中需要用java.net.URLDecoder解码 5.结果演示 : 在浏览器中输入:http://localhost:8080/AjaxServletJson/ 先输入,然后点击按钮:源代码下载:参考资料:
1.jquery $.ajax参考手册:http://www.w3school.com.cn/jquery/ajax_ajax.asp
未经允许不得用于商业目的