Ajax请求

Ajax请求;

1:简介;

1:AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。
2:AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
3:Ajax 不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的Web应用程序的技术。
4:在 2005 年,Google 通过其 Google Suggest 使 AJAX 变得流行起来。Google Suggest能够自动帮你完搜索单词。
5:Google Suggest 使用 AJAX 创造出动态性极强的 web 界面:当您在谷歌的搜索框输入关键字时,JavaScript 会把这些字符发送到服务器,然后服务器会返回一个搜索建议的列表。
6:就和国内百度的搜索框一样!
7:传统的网页(即不用ajax技术的网页),想要更新内容或者提交一个表单,都需要重新加载整个网页。
8:使用ajax技术的网页,通过在后台服务器进行少量的数据交换,就可以实现异步局部更新。
9:使用Ajax,用户可以创建接近本地桌面应用的直接、高可用、更丰富、更动态的Web用户界面。

2:伪造Ajax

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

1、新建一个module :sspringmvc-06-ajax , 导入web支持!
2、编写一个 ajax-frame.html 使用 iframe 测试,感受下效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ifram测试体验无刷新</title>
</head>
<body>

<script>
    function go() {
        var url = document.getElementById("url").value;
        console.log(url);
        document.getElementById("iframe1").src = url;

    }
</script>

<div>
    <p>请输入地址:</p>

   <p>
       <input type="text" id="url" value="https://www.bilibili.com/">
       <input type="submit" value="提交" onclick="go()">
   </p>
</div>


<div>
    <iframe id="iframe1" style="width: 100%;height: 500px;"></iframe>
</div>

</body>
</html>

测试结果

在这里插入图片描述

3:功能:

利用Ajax可以做

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

需要下载jQuery包,并导入

在这里插入图片描述

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
       http://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">

    <!--自动扫描包-->
    <context:component-scan base-package="com.baidu.controller"/>

    <mvc:annotation-driven/>

    <!--静态资源过滤-->
    <mvc:default-servlet-handler/>
    

    <!-- 视图解析器 -->
    <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:编写一个AjaxController

//失去焦点
@RequestMapping("/test1")
public void test1(String name, HttpServletResponse response) throws IOException {
    System.out.println("test1:parma==>"+name);

    if ("yaoji".equals(name)){
        response.getWriter().print("true");
    }else {
        response.getWriter().print("false");
    }

}

3:导入jQuery的包;
4:编写一个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.6.0.js"></script>

    <script>
      function a1(){
        $.post({
          url:"${pageContext.request.contextPath}/test1",
          data:{'name':$("#userName").val()},
          success:function (data,status) {
            alert(data);
            console.log(status);
          }
        });
      }
    </script>
  </head>
  <body>

  <%--onblur:失去焦点触发事件--%>
  用户名: <input type="text" id="userName" onblur="a1()"/>


  </body>
</html>

5:启动tomcat测试!打开浏览器的控制台,当我们鼠标离开输入框的时候,可以看到发出了一个ajax的请求!是后台返回给我们的结果!测试成功!

**

获取集合对象,展示到前端页面

**

1:实体类;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private String name;
    private int age;
    private String sex;

}

2:编写AjaxController,添加数据;

//添加数据
@RequestMapping("/test2")
public List<User> test2(){
    List<User> userList = new ArrayList<>();
    userList.add(new User("铁锤一号:",1,"男"));
    userList.add(new User("铁锤二号:",14,"女"));
    userList.add(new User("铁锤三号:",31,"男"));

    return userList;
}

3:编写一个test.jsp前端页面;

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>

    <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>

    <script>
        $(function () {
            $('#btn').click(function(){
                // console.log("111");

                $.post("${pageContext.request.contextPath}/test2",function (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>"
                    }

                    $("#content").html(html);
                })


            });
        })
    </script>

</head>
<body>


<input type="submit" value="加载数据!" id="btn">

<table>
    <tr>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
    </tr>

    <tbody id="content">
    <!--数据:后台加载!-->

    </tbody>


</body>
</html>

测试结果:点击按钮显示数据到前端:

在这里插入图片描述

4:

**

注册提示信息;

**

1:我们写一个Controller

//测试登录页面;
@RequestMapping("/a3")
public String ajax3(String name,String pwd){
    String msg = "";

    //模拟数据库中存在数据
    if (name!=null){
        if ("admin".equals(name)){
            msg = "OK";
        }else {
            msg = "用户名输入错误";
        }
    }

    if (pwd!=null){
        if ("root".equals(pwd)){
            msg = "OK";
        }else {
            msg = "密码输入有误";
        }
    }
    return msg; //由于@RestController注解,将msg转成json格式返回
}

2:前端页面:login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    
    <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>

    <script>
           function a1() {
               $.post({
                   url:"${pageContext.request.contextPath}/a3",
                   data:{'name':$("#name").val()},
                   success:function (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) {
                       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="password" id="pwd" onblur="a2()">
    <span id="pwdInfo"></span>
</p>

</body>
</html>

4:测试结果:

在这里插入图片描述

相关文章

$.AJAX()方法中的PROCESSDATA参数 在使用jQuery的$.ajax()方...
form表单提交的几种方式 表单提交方式一:直接利用form表单提...
文章浏览阅读1.3k次。AJAX的无刷新机制使得在注册系统中对于...
文章浏览阅读1.2k次。 本文将解释如何使用AJAX和JSON分析器在...
文章浏览阅读2.2k次。/************************** 创建XML...
文章浏览阅读3.7k次。在ajax应用中,通常一个页面要同时发送...