zoukankan      html  css  js  c++  java
  • SpringMVC-09-Ajax技术

    9. Ajax技术

    简介

    • AJAX=Asynchronous JavaScript and XML (异步的JavaScript和XML)
    • AJAX是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
    • Ajax不是新的编程语言,而是一种用于创建更快更好以及交互性更强的Web应用程序的技术。
    • 举例:在搜索框输入关键词时,JavaScript会把这些字符发送到服务器,然后服务器返回一个搜索建议的列表。

    伪造Ajax

    我们可以使用前端的一个标签来伪造一个ajax的样子:iframe

    1. 新建一个module,springmvc-06-ajax,导入web支持

    2. 编写一个ajax-frame.html使用iframe测试

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <title>iframe测试 体验页面无刷新</title>
          <script>
              function go() {
                  //所有的值 变量 提前获取
                  var url=document.getElementById("url").value;
                  document.getElementById("iframe1").src="url";
              }
      
          </script>
      
      </head>
      <body>
      <div>
          <p>请输入地址:</p>
          <p>
              <input type="text" id="url">
              <input type="button" value="提交" onclick="go()">
          </p>
      
      </div>
      <div>
          <iframe id="iframe1" style="100%;height:500px"></iframe>
      </div>
      </body>
      </html>
      

    利用Ajax可以做:

    1. 注册时,输入用户名自动检测用户是否存在
    2. 登录时,提示用户名密码错误
    3. 删除数据行时,将行ID发送到后台,后台在数据库中删除,页面DOM将数据行也删除

    jQuery.ajax

    • 直接使用jQuery提供的ajax
    • Ajax的核心是XMLHttpRequest对象(XHR)。XHR为服务器发送请求和解析服务器响应提供了接口,能够异步方式从服务器上获取新数据。
    • jQuery提供了多个与AJAX有关的方法
    • 通过jQueryAJAX方法,能够使用HTTP Get和HTTP Post从远程服务器上请求文本、html、xml或json,同时把这些外部数据直接载入网页的被选元素中。
    • jQuery Ajax的本质就是XMLHttpRequest,对它进行了封装。

    jQuery是一个库,包含大量JS的函数(方法)

    在这里插入图片描述

    来做个简单的测试,使用最原始的HttpServletRequest处理:

    1. 配置web.xml和springmvc的配置文件

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:context="http://www.springframework.org/schema/context"
             xmlns:mvc="http://www.springframework.org/schema/mvc"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
              https://www.springframework.org/schema/beans/spring-beans.xsd
              http://www.springframework.org/schema/context
              https://www.springframework.org/schema/context/spring-context.xsd
              http://www.springframework.org/schema/mvc
              https://www.springframework.org/schema/mvc/spring-mvc.xsd">
      
          <!--自动扫描包 让指定包下的注解生效 由IOC容器统一管理-->
          <context:component-scan base-package="com.kuang.controller"/>
      
          <!--让spring mvc不处理静态资源  .css .js -->
          <mvc:default-servlet-handler/>
      
          <!--annotation-driven帮助我们自动完成handlermapper和adapter实例的注入-->
          <mvc:annotation-driven/>
      
          <!--视图解析器: 模版引擎-->
          <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
              <property name="prefix" value="/WEB-INF/jsp/"/>
              <property name="suffix" value=".jsp"/>
          </bean>
      
      
      
      </beans>
      
    2. index.jsp

      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
        <head>
          <title>$Title$</title>
            <script src="${pageContext.request.contextPath}/static/js/jquery-3.5.1.js">
            </script>
      
            <script>
                function a(){
                    $.post({
                        url:"${pageContext.request.contextPath}/a1",
                        data:{"name":$("#username").val()},
                        success:function (data,status) {
                            console.log("data="+data);
                            console.log("status="+status);
                        }
                        })
                }
      
            </script>
        </head>
        <body>
        <%--失去焦点的时候发起一个请求(携带信息)--%>
        用户名:<input type="text" id="username" onblur="a()">
        </body>
      </html>
      
    3. AjaxController.java

      @RequestMapping("/a1")
      public void a1(String name, HttpServletResponse response) throws IOException {
          System.out.println("a1.param:"+name);
          if("huba".equals(name)){
              response.getWriter().print("true");
          }else {
              response.getWriter().print("false");
          }
      }
      

    架构解析:

    在这里插入图片描述

    异步加载数据测试案例

    1. 新建pojo包下的user实体类

      @Data
      @AllArgsConstructor
      @NoArgsConstructor
      public class User {
          private String name;
          private int age;
          private String sex;
      }
      
    2. 增加controller:AjaxController.java

      @RequestMapping("/a2")
      public List<User> a2(){
          List<User> userList = new ArrayList<User>();
          //添加数据
          userList.add(new User("狂神说java",1,"男"));
          userList.add(new User("狂神说前端",1,"女"));
          userList.add(new User("狂神说运维",1,"男"));
          return userList;
      }
      
    3. 写页面test2.jsp

      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
          <title>Title</title>
          <script src="${pageContext.request.contextPath}/static/js/jquery-3.5.1.js"></script>
          <script>
              $(function () {
                  $("#btn").click(function () {
                      //简写
                      //$.post(url,param,success) param可省略
                      $.post("${pageContext.request.contextPath}/a2", function (data) {
                          // console.log(data);
                          var html="<>";
                          for (let i = 0; i < data.length; i++) {
                              html+="<tr>"+
                                  "<td>"+data[i].name+"</td>"+
                                  "<td>"+data[i].age+"</td>"+
                                  "<td>"+data[i].sex+"</td>"+
                                  "<tr>";
                          }
                          console.log(data);
                          $("#content").html(html);
                      });
      
                  });
              });
      
              
          </script>
      </head>
      <body>
      
      <input type="button" value="加载数据" id="btn">
      <table>
          <tr>
              <td>姓名</td>
              <td>年龄</td>
              <td>性别</td>
          </tr>
          <tbody id="content">
              <%--数据在后台--%>
              
          </tbody>
      </table>
      
      </body>
      </html>
      

    注册提示效果

    测试:平时注册时,输入框后面的实时提示是如何做到的?

    1. 写一个controller

      @RequestMapping("/a3")
      public String a3(String name,String pwd){
          String msg="";
          if(name!=null){
              //实际上,admin的数据应从数据库查询
              if("admin".equals(name))
                  msg="ok";
              else
                  msg="no";
          }
          if(pwd!=null){
              if("123456".equals(pwd))
                  msg="ok";
              else
                  msg="no";
          }
          return msg;
      
      }
      
    2. 写一个登录页面 login.jsp

      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
          <title>登录页面</title>
          <script src="${pageContext.request.contextPath}/static/js/jquery-3.5.1.js"></script>
      
          <script>
              function a1() {
                  $.post({
                      url:"${pageContext.request.contextPath}/a3",
                      data:{"name":$("#name").val()},
                      success:function (data) {
                          // console.log(data);
                          if(data.toString()==='ok'){
                              $("#userInfo").css("color","green");
                          }else
                              $("#userInfo").css("color","red");
                          $("#userInfo").html(data);
                      }
                  })
      
      
              }
              function a2() {
                  $.post({
                      url:"${pageContext.request.contextPath}/a3",
                      data:{"pwd":$("#pwd").val()},
                      success:function (data) {
                          // console.log(data);
                          if(data.toString()==='ok'){
                              $("#pwdInfo").css("color","green");
                          }else
                              $("#pwdInfo").css("color","red");
                          $("#pwdInfo").html(data);
                      }
                  })
      
      
              }
          </script>
      </head>
      <body>
      <p>
          用户名:<input type="text" id="name" onblur="a1()">
          <span id="userInfo"></span>
      </p>
      <p>
          密码:<input type="text" id="pwd" onblur="a2()">
          <span id="pwdInfo"></span>
      </p>
      </body>
      </html>
      

  • 相关阅读:
    System.InvalidOperationException异常的处理!vs15版
    五子棋项目的实现(四)具体的总结
    五子棋项目的实现(三)人机对战类的具体设计
    五子棋项目的实现(二)博弈树算法的描述
    五子棋项目的实现(一)
    java Exception和Error的区别
    java内存分配实例
    expdp与impdp
    SQL*PLUS下使用AUTOTRACE、sql顾问、实时sql监控
    Linux下如何将数据库脚本文件从sh格式变为sql格式
  • 原文地址:https://www.cnblogs.com/CodeHuba/p/13665898.html
Copyright © 2011-2022 走看看