JavaWeb_Ajax通过JQuery和原生js异步传输数据

 

 

  菜鸟教程  传送门

  AJAX 优点:在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容

  

  XMLHttpRequest 对象  传送门

 

 

  

 

  (一) [JQuery]定时发送ajax请求

  (二) [JQuery]发送ajax时客户端服务端进行数据传递

  (三) [原生JS]使用原生js代码完成ajax请求

  (四)通过Ajax检测用户注册信息重复

 

 

[JQuery]定时发送ajax请求  JQuery.ajax()文档

 

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-3.3.1.min.js"></script>

<script type="text/javascript">

//2000ms调用一次这个方法
setInterval("callAjax()",2000);
function callAjax(){
    $.ajax({
//         alert("ajax");ajaxrequest
        url:"${pageContext.request.contextPath }/ajaxrequest",
        cache:false,    //去除缓存
        type:"get",
        success:function(msg){
            //将数据刷新到页面上
            $("#msg").append(msg);
        }
    });
}


</script>

</head>
<body>

<form action="${pageContext.request.contextPath}/login_do" method="post">
用户名:<input type="text" name="username" /><br/>
密码:<input type="password" name="password" /><br/>
<input type="submit" value="登录" />
</form>

<div id ="msg"></div>

</body>
</html>
ajax.jsp

 

package com.Gary.controller;

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("/ajaxrequest")
public class AjaxServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //System.out.println("发送ajax请求");
        response.setContentType("text/html; charset=utf-8");
        response.getWriter().append("ajax数据");
        
    }


}
AjaxServlet.java

 

  客户端发送get请求由AjaxServlet.java中doGet去接收

 

 

[JQuery]发送ajax时客户端服务端进行数据传递

 

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-3.3.1.min.js"></script>

<script type="text/javascript">

//2000ms调用一次这个方法
setInterval("callAjax()",2000);
function callAjax(){
    $.ajax({
//         alert("ajax");ajaxrequest
//        发送中文需要对中文做一个编码使用encodeURI()
        url:encodeURI("${pageContext.request.contextPath }/ajaxrequest?data=我是客户端发送过来的数据"),
        cache:false,    //去除缓存
        type:"get",
        success:function(msg){
            //将数据刷新到页面上
            $("#msg").append(msg);
        }
    });
}


</script>

</head>
<body>

<form action="${pageContext.request.contextPath}/login_do" method="post">
用户名:<input type="text" name="username" /><br/>
密码:<input type="password" name="password" /><br/>
<input type="submit" value="登录" />
</form>

<div id ="msg"></div>

</body>
</html>
ajax.jsp

 

package com.Gary.controller;

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("/ajaxrequest")
public class AjaxServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //System.out.println("发送ajax请求");
        System.out.println("收到了ajax请求:"+request.getParameter("data"));
        response.setContentType("text/html; charset=utf-8");
        response.getWriter().append("ajax数据");
        
    }


}
AjaxServlet.java

 

  中文编码处理时使用encodeURI()方法

  服务端数据的交互也通过AjaxServlet.java中的doGet去接收

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //System.out.println("发送ajax请求");
        System.out.println("收到了ajax请求:"+request.getParameter("data"));
        response.setContentType("text/html; charset=utf-8");
        response.getWriter().append("ajax数据");
    }

 

 

【原生js】使用原生js代码完成ajax请求

 

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-3.3.1.min.js"></script>

<script type="text/javascript">

//2000ms调用一次这个方法
setInterval("callAjax()",2000);
function callAjax(){
    //alert("123123");
    var xmlhttp = new XMLHttpRequest();
    //xmlHttp.open("post", url, true);    第三个:是否是异步请求    加随机数去处理缓存
    xmlhttp.open("GET",encodeURI("${pageContext.request.contextPath }/ajaxrequest?data=我是客户端发送的数据&"+Math.random()),true);
    xmlhttp.send();
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState==4 && xmlhttp.status==200){
            //得到了服务器端的响应
            $("#msg").append(xmlhttp.responseText);
        }
    }
}


</script>

</head>
<body>

<form action="${pageContext.request.contextPath}/login_do" method="post">
用户名:<input type="text" name="username" /><br/>
密码:<input type="password" name="password" /><br/>
<input type="submit" value="登录" />
</form>

<div id ="msg"></div>

</body>
</html>
ajax.jsp

 

package com.Gary.controller;

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("/ajaxrequest")
public class AjaxServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //System.out.println("发送ajax请求");
        System.out.println("收到了ajax请求:"+request.getParameter("data"));
        response.setContentType("text/html; charset=utf-8");
        response.getWriter().append("ajax数据");
        
    }


}
AjaxServlet.java

 

setInterval("callAjax()",2000);
function callAjax(){
    //alert("123123");
    var xmlhttp = new XMLHttpRequest();
    //xmlHttp.open("post", url, true);    第三个:是否是异步请求    加随机数去处理缓存
    xmlhttp.open("GET",encodeURI("${pageContext.request.contextPath }/ajaxrequest?data=我是客户端发送的数据&"+Math.random()),true);
    xmlhttp.send();
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState==4 && xmlhttp.status==200){
            //得到了服务器端的响应
            $("#msg").append(xmlhttp.responseText);
        }
    }
}

 

 

通过Ajax检测用户注册信息重复

 

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
//     当网页加载完后会调用这个函数
    $(function(){
//         当username失去焦点的时候执行
        $("input[name='username']").blur(verifyUsername);
    });
    
    function verifyUsername(){
//         $("input[name='username']").val()
        $.ajax({
            url:encodeURI("${pageContext.request.contextPath }/verifyUsername"),
            type:"post",
            data:{
//                 验证用户名是否存在
                username:$("input[name='username']").val()
            },
            cache:false,
            dataType:"json",
            success:function(msg){
                //alert(msg.isSuccess);
                if(msg.isSuccess){
                    alert("用户名可以用!");
                }else{
                    alert("用户名重复!");
                }
                
            }
        });
    }
</script>

</head>
<body>

<%
if(request.getAttribute("msg")!=null)
    out.println(request.getAttribute("msg")+"<br/>");
%>

注册
<hr/>

<form action="<%=request.getContextPath() %>/register_do" method="post">
用户名:<input type="text" name="username" /><br/>
密码:<input type="password" name="password" /><br/>
年龄:<input type="text" name="age" /><br/>
性别: 男<input type="radio" name="sex" value="男" checked="checked"/><input type="radio" name="sex" value="女" /><br/>
<input type="submit" value="注册" />
</form>

</body>
</html>
register.jsp

 

package com.Gary.service;

import com.Gary.dao.UserDao;
import com.Gary.model.User;

public class UserService {
    //处理注册请求
    public boolean register(String username,String password,int age ,String sex) {
        UserDao userDao = new UserDao();
        boolean isExist =userDao.isExist(username);
        if(isExist)    
            return false;
        else 
            userDao.addUser(username, password, age, sex);
        return true;
    }
    
    public User login(String username,String password) {
        return new UserDao().getUserByUP(username, password);
    }
    
    public boolean isExist(String username) {
        return new UserDao().isExist(username);
    }
    
}
UserService.java

 

package com.Gary.controller;

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;

import com.Gary.service.UserService;


@WebServlet("/verifyUsername")
public class VerifyUsernameServlet extends HttpServlet {
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        UserService service = new UserService();
        boolean isExist = service.isExist(username);
        response.getWriter().append("{\"isSuccess\":"+!isExist+"}");
    }

}
VerityUsernameServlet.java

 

  其他页面代码(MVC)管理员后台商品查询demo

  通过Ajax异步请求在鼠标离焦username标签时将请求发送至verifyUsername并自动校验数据库中用户ID

  

<script type="text/javascript">
//     当网页加载完后会调用这个函数
    $(function(){
//         当username失去焦点的时候执行
        $("input[name='username']").blur(verifyUsername);
    });
    
    function verifyUsername(){
//         $("input[name='username']").val()
        $.ajax({
            url:encodeURI("${pageContext.request.contextPath }/verifyUsername"),
            type:"post",
            data:{
//                 验证用户名是否存在
                username:$("input[name='username']").val()
            },
            cache:false,
            dataType:"json",
            success:function(msg){
                //alert(msg.isSuccess);
                if(msg.isSuccess){
                    alert("用户名可以用!");
                }else{
                    alert("用户名重复!");
                }
                
            }
        });
    }
</script>

 

  

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        UserService service = new UserService();
        //service.isExist()判断有无重复用户ID
        boolean isExist = service.isExist(username);
        //有的话返回false表示不允许用户注册,反之为true
        response.getWriter().append("{\"isSuccess\":"+!isExist+"}");
    }

 

  设置当Ajax异步校验成功返回msg类型时使用dataType:"xxx"并在doPost中的isSuccess使用" "引号引起来

  中文编码处理时使用encodeURI()方法

  

 

posted @ 2019-01-24 22:27  Cynical丶Gary  阅读(857)  评论(0编辑  收藏  举报