jquery访问servlet并返回数据到页面的方法

1. servlet:AjaxServlet.java如下:

复制代码 代码如下:

package com.panlong.servlet

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; 

public class AjaxServlet extends HttpServlet { 
    private static final long serialVersionUID = 1L; 
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException { 
        Integer total = (Integer) req.getSession().getAttribute("total"); 
        int temp = 0; 
        if(total == null ){ 
            temp = 1; 
        }else{ 
            temp = total.intValue() + 1; 
        } 
    req.getSession().setAttribute("total",temp); 
        try { 
            //1.取参数 
            resp.setContentType("text/html;charset=GBK"); 
            PrintWriter out = resp.getWriter(); 
            String old = req.getParameter("name"); 
            //2.检查参数是否有问题 
            //String name = new String(old.getBytes("iso8859-1"),"UTF-8"); 
            String name = URLDecoder.decode(old,"UTF-8"); 
            if("".equals(old) || old == null){ 
                out.println("用户名必须输入"); 
            }else{ 
                if("liling".equals(name)){ 
                    out.println("恭喜登录成功"); 
                    return; 
                }else{ 
                    out.println("该用户名未注册,您可以注册["+name+"]这个用户名"+temp); 
                } 
            } 
        } catch (Exception e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } 
        //3.检验操作 
    } 
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException { 
        doGet(req, resp); 
    } 
}

2. verify.js如下:

复制代码 代码如下:

function verify(){ 
    //解决中文乱码问题的方法1,页面端发出的数据作一次encodeURI,服务端使用new String(old.getBytes("iso8859-1"),"UTF-8"); 
    //解决中文乱码问题的方法2,页面端发出的数据作两次encodeURI,服务端使用String name = URLDecoder.decode(old,"UTF-8"); 
    var url = "servlet/AjaxServlet?name="+encodeURI(encodeURI($("#userName").val())); 
    url = convertURL(url); 
    $.get(url,null,function(data){ 
        $("#result").html(data); 
    }); 

//给url地址增加时间蒫,难过浏览器,不读取缓存 
function convertURL(url){ 
    //获取时间戳 
    var timstamp = (new Date()).valueOf(); 
    //将时间戳信息拼接到url上 
    if(url.indexOf("?") >=0){ 
        url = url + "&t=" + timstamp; 
    }else{ 
        url = url + "?t=" + timstamp; 
    } 
    return url; 
}

3. 前台页面如下:

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wfyxyz.html