Ajax快速入门

2019-04-30  本文已影响0人  伍陆柒_

AJAX:即“Asynchronous Javascript And XML”(异步的JavaScript和XML),是指一种创建交互式网页应用的网页开发技术,尤其是在一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。

传统Web开发
World Wide Web(简称Web):是随着Internet的普及使用而发展起来的一门技术,其开发模式是一种请求→刷新→响应的模式,每个请求由单独的一个页面来显示,发送一个请求就会重新获取这个页面。

!

验证用户名是否注册

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
        <title>$Title$</title>
        <script src="js/jq.js" type="text/javascript" charset="utf-8"></script>
      <script>
          $(function () {
              $('input[name=username]').blur(function () {
                  // 检查用户名是否可以被注册,如果不可以,响应失败信息,否则响应成功信息
                  // 发送ajax请求
                  if($('input[name=username]').val() != null && $('input[name=username]').val().trim() != ''){
                      $.ajax({
                          /*url指定接收请求的地址*/
                          url : "${pageContext.request.contextPath}/checkUsername",
                          /*data填写发送的数据*/
                          data : {
                              "name" :  $('input[name=username]').val()
                          },
                          // type指定请求类型
                          type : "get",
                          // dataType指定响应信息格式
                          dataType : "json",
                          // 指定成功的回调函数,res是响应回来的信息
                          success : function (res) {
                              if(res == 0){
                                  $('#msg').html("注册失败").css('color','red');
                                  $('button').attr('disabled','disabled');
                              }else{
                                  $('#msg').html("注册成功").css('color','green');
                                  $('button').removeAttr('disabled');
                              }
                          },
                          // 指定失败的回调函数
                          error : function(){
                              alert("服务响应失败");
                          },
                          // 异步请求
                          async : true
                      })
                  }

              })
          })
      </script>
  </head>
  <body>
    <h1>Reg Page</h1>
    <form action="${pageContext.request.contextPath}/reg" method="post">
        <input type="text" name="username" placeholder="用户名"><span id="msg"></span><br><br>
        <input type="password" name="password" placeholder="密码">
        <button>注册</button>
    </form>
  </body>
</html>

CheckUsernameServlet.java

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 java.io.IOException;

@WebServlet(name = "CheckUsernameServlet",urlPatterns = "/checkUsername")
public class CheckUsernameServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求参数
        String name = request.getParameter("name");
        // 调dao查询该用户名是否存在
        if("mike".equals(name)){
            // 失败
            response.getWriter().println(0);
        }else{
            response.getWriter().println(1);
        }
    }
}

根据id查询用户和查询全部用户

把对象序列化成字符串,需要使用jacksonfastjson,可以自己到maven库下载
serch.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jq.js" type="text/javascript" charset="utf-8"></script>
    <script>
        $(function () {
            $('#serch1').click(function () {
                $.ajax({
                    url : "${pageContext.request.contextPath}/serchById",
                    data:{
                        "userid" : $('#userid').val()
                    },
                    type : 'get',
                    dataType : 'json',// 解析json字符串
                    success : function (res) {
                        $('#box').html(res.id+","+res.name+","+res.sex+","+res.age)
                    },
                    error : function () {
                        alert("响应失败")
                    },
                    async : true
                })
            })

            $('#serch2').click(function () {
                $.ajax({
                    url : "${pageContext.request.contextPath}/serchAll",
                    data:{},
                    type : 'get',
                    dataType : 'json',// 解析json字符串
                    success : function (res) {
                        $('#box').html('');
                        for(i in res){
                            $('#box').append(res[i].name+","+res[i].age+"<br>")
                        }
                    },
                    error : function () {
                        alert("响应失败")
                    },
                    async : true
                })
            })

        })
    </script>
</head>
<body>
    <h1>Serch Page</h1>
    <p>
        <input type="text" id="userid">
        <button type="button" id="serch1">查询</button>
        <button type="button" id="serch2">查询全部</button>
    </p>
    <div id="box"></div>
</body>
</html>

SerchByIdServlet.java

import com.alibaba.fastjson.JSON;
import com.neuedu.pojo.Userinfo;

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 java.io.IOException;

@WebServlet(name = "SerchByIdServlet",urlPatterns = "/serchById")
public class SerchByIdServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求参数
        String userid = request.getParameter("userid");
        // 调dao层查询该id员工所有信息
        Userinfo userinfo = new Userinfo();
        userinfo.setId(Integer.parseInt(userid));
        userinfo.setAge(30);
        userinfo.setName("leo");
        userinfo.setSex("男");
        // 响应ajax请求
        //  JSON.toJSONString会把对象序列化成json字符串
        String str = JSON.toJSONString(userinfo);
        System.out.println(str);
        response.getWriter().println(str);
    }
}

SerchAllServlet.java

import com.alibaba.fastjson.JSON;
import com.neuedu.pojo.Userinfo;

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 java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "SerchAllServlet",urlPatterns = "/serchAll")
public class SerchAllServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Userinfo userinfo1 = new Userinfo();
        userinfo1.setId(1001);
        userinfo1.setName("tom");
        userinfo1.setSex("man");
        userinfo1.setAge(30);
        Userinfo userinfo2 = new Userinfo();
        userinfo2.setId(1002);
        userinfo2.setName("lucy");
        userinfo2.setSex("girl");
        userinfo2.setAge(33);
        Userinfo userinfo3 = new Userinfo();
        userinfo3.setId(1003);
        userinfo3.setName("lilei");
        userinfo3.setSex("man");
        userinfo3.setAge(20);

        List<Userinfo> list = new ArrayList<>();
        list.add(userinfo1);
        list.add(userinfo2);
        list.add(userinfo3);
        String str = JSON.toJSONString(list);
        System.out.println(str);
        response.getWriter().println(str);
    }
}

ajax简化写法

        <script>
            $(function () {
                $('#reg').click(function () {
                    $.post(
                            "${pageContext.request.contextPath}/user/reg",
                            {
                                "username": $('input[name=username]').val(),
                                "password":$('input[name=password]').val()
                            },
                            function success(res) {
                                if(res == 0){
                                    $('#msg').html("注册失败").css('color','red');
                                }else{
                                    window.location.href = "${ pageContext.request.contextPath }/gologin";
                                }
                            },
                            "json"
                    );
                })
            })
        </script>
上一篇下一篇

猜你喜欢

热点阅读