• Jquery+ajax+json+servlet原理和Demo


    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 + "/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    	<head>
    		<base href="<%=basePath%>">
    
    		<title>Jquery Ajax Json Servlet Demo</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/jquery.min.js"></script>
    		<script type="text/javascript">
    	       function jsonAjaxPost(){
    	         var userNameObj=$("#username").val();
    	         var contentObj=$("#content").val();
                 $.ajax({
                   type:"post",//请求方式
                   url:"jsonAjaxAction?userName="+encodeURI(encodeURI(userNameObj))
                       +"&content="+encodeURI(encodeURI(contentObj)),//发送请求地址
                   timeout:30000,//超时时间:30秒
                   dataType:"json",//设置返回数据的格式
                   //请求成功后的回调函数 data为json格式
                   success:function(data){
                      $("#resultJsonText").text("你的名字:"+data.yourName+"  你输入的内容:"+data.yourContent);
                  },
                  //请求出错的处理
                  error:function(){
                            alert("请求出错");
                  }
               });
              }
    	</script>
    	</head>
    	<body>
    	<form id="form1" method="post">
    		<p>
    			评论:
    		</p>
    		<p>
    			姓名:
    			<input type="text" name="username" id="username" />
    		</p>
    		<p>
    			内容:
    			<textarea name="content" id="content" rows="2" cols="20"></textarea>
    		</p>
    		<p>
    			<input type="button" id="send" value="提交" onclick="jsonAjaxPost()" />
    		</p>
    	</form>
    	<div class="comment">
    		返回数据:
    		<p id="resultJsonText"></p>
    	</div>
    	<div id="resText">
    	</div>
    	</body>
    </html>


    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

    <?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">
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <servlet>
    		<servlet-name>jsonAjaxAction</servlet-name>
    		<servlet-class>com.njupt.zhb.test.JsonAjaxServlet</servlet-class>
    	</servlet>
    	<servlet-mapping>
    		<servlet-name>jsonAjaxAction</servlet-name>
    		<url-pattern>/jsonAjaxAction</url-pattern>
    	</servlet-mapping>
    </web-app>
    


    4.其他
    1.需要导入jquery.min.js
    2.注意乱码的解决方案:
     2.1:js中对字符串进行编码,即:encodeURI(encodeURI(userNameObj))
     2.2:在Servlet中需要用java.net.URLDecoder解码
    5.结果演示
    在浏览器中输入:http://localhost:8080/AjaxServletJson/
    先输入,然后点击按钮:

    源代码下载:http://download.csdn.net/detail/nuptboyzhb/6193851
    参考资料

    1.jquery $.ajax参考手册:http://www.w3school.com.cn/jquery/ajax_ajax.asp

    未经允许不得用于商业目的

  • 相关阅读:
    349元我们应该有什么样的期待原道N12豪华版 RK2906入手初体验
    漫谈国内智能手机市场现状
    将AltiumDesigner(Protel升级版)的PCB设计打造成利器——订制应用、操作、过滤表达式及其他一些微操作
    modelsim se 10.1a 下载与破解
    shell配置,选择,环境变量修改(ORACLE_HOME,ORACLE_SID),无法使用sqlplus
    /ibm/fan
    TrackPoint_configure_ThinkPad_squeeze(0616.2011)
    来个狠的
    JDBC for MSSql2005 简单示例
    oracle使用指南
  • 原文地址:https://www.cnblogs.com/pangblog/p/3297112.html
Copyright © 2020-2023  润新知