码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC-AJAX

时间:2020-09-17 21:58:28      阅读:35      评论:0      收藏:0      [点我收藏+]

标签:service   主动权   bin   pre   public   test   pwd   验证   name   

AJAX

1. AJAX简介

AJAX = Asynchronous JavaScript and XML (异步的JavaScript和XML)

Ajax不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的Web应用程序的技术

增强B/S的体验性(Browser/Service)

B/S:未来的主流,并且会爆发式持续增长

产品链:H5 + 网页 + 客户端 + 手机端 (Android + IOS) + 小程序

请求的类型: xhr

2. 利用iframe伪造AJAX

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

    <script>
        function go() {
            //所有的变量, 提前获取
            let url = document.getElementById("url").value;
            document.getElementById("iframe1").src=url;
        }
    </script>

</head>
<body>

<div>
    <p>请输入地址:</p>
    <p>
        <input type="text" id="url" value="http://www.baidu.com">
        <input type="button" value="提交" onclick="go()">
    </p>

</div>


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

</body>
</html>

3. 利用js实现AJAX

1. 引入jquery

在jsp的head标签内写

<script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.min.js"></script>

2. 编写jsp

<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/9/10
  Time: 18:54
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>

    <script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.min.js"></script>

    <script>
      function a() {
        $.post({
            url: "${pageContext.request.contextPath}/a1",
            data: {"name" : $("#username").val()},
            success: function (data) {
                alert(data);
            }
        })
      }

    </script>

  </head>
  <body>

  <%--失去焦点的时候, 发起一个请求(携带信息)到后台, 调用a()--%>
  用户名: <input type="text" id="username" onblur="a()"/>
  </body>
</html>

3. 编写controller

package com.wang.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class AjaxController {

    @RequestMapping("/t1")
    public String test() {
        return "hello";
    }

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

4. 流程分析

graph LR id1[input] id2[function a] id3[url: localhost:8080/a1 <br/>data: &#123key:value&#125 <br/>callback: function&#40data&#41] id4[&#47a<br/>true or false] id1 --失去焦点--> id2 id2 --ajax.post--> id3 id4 --data:json--> id3 subgraph 前端 id1 id2 id3 end subgraph 后端 id4 end

ajax把主动权交给了前端 ==> callback函数

4. AJAX从后台加载数据

1. 创建实体类

package com.wang.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int age;
    private String sex;
}

2. 在controller中将数据传递给前端

package com.wang.controller;

import com.wang.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class AjaxController {

    @RequestMapping("/t1")
    public String test() {
        return "hello";
    }

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

    @RequestMapping("/a2")
    public List<User> a2() {
        ArrayList<User> userArrayList = new ArrayList<>();
        //添加数据
        userArrayList.add(new User("wang_1", 1, "male"));
        userArrayList.add(new User("wang_2", 2, "female"));
        userArrayList.add(new User("wang_3", 3, "male"));
        return userArrayList;
    }
}
  • 如果要使用AJAX, 此处controller不能调用视图解析器, 要返回json供AJAX中的data参数调用
  • 不使用视图解析器的方法: 类上写@RestController或者方法上写@ResponseBody

3. 使用ajax调用并显示

<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/9/11
  Time: 10:41
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>

    <script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.min.js"></script>

    <script>
        //最外面的function保证窗口一打开里面的函数就运行, 一定要写!
        $(function () {
            $("#btn").click(function () {
                /*
                $.post(url, param[可以省略], success
                 */
                $.post("${pageContext.request.contextPath}/a2",function (data) {
                    //console.log(data);
                    let 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>

<body>

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

<table>
    <tr>
        <td>姓名</td>
        <td>年龄</td>
        <td>性别</td>
    </tr>
    <tbody id="content">
        <%--数据: 后台--%>
    </tbody>
</table>

</body>
</html>

注意

  • js中, 最外面的function保证窗口一打开里面的函数就运行, 一定要写!(相当于入口函数)

  • 使用html方法, 直接拼接html语句到tbody中

  • function(data){}是回调函数,ajax可以执行则执行其中的函数!

5. AJAX用户名验证

1. 解决中文乱码,配置Spring

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <constructor-arg value="UTF-8"/>
        </bean>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                    <property name="failOnEmptyBeans" value="false"/>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

2. 添加controller层的功能

package com.wang.controller;

import com.wang.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class AjaxController {

    @RequestMapping("/t1")
    public String test() {
        return "hello";
    }

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

    @RequestMapping("/a2")
    public List<User> a2() {
        ArrayList<User> userArrayList = new ArrayList<>();
        //添加数据
        userArrayList.add(new User("wang_1", 1, "male"));
        userArrayList.add(new User("wang_2", 2, "female"));
        userArrayList.add(new User("wang_3", 3, "male"));
        return userArrayList;
    }

    @RequestMapping("/a3")
    public String a3(String name, String pwd) {
        String msg = "";
        if (name != null){
            //"admin"这些数据应该在数据库中查
            if("admin".equals(name)) {
                msg = "ok";
            } else {
                msg = "用户名有误";
            }
        }

        if (pwd != null){
            //"admin"这些数据应该在数据库中查
            if("123456".equals(pwd)) {
                msg = "ok";
            } else {
                msg = "密码有误";
            }
        }
        return msg;
    }
}

3. 编写前端代码

<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/9/11
  Time: 11:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>

    <script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.min.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="text" id="pwd" onblur="a2()">
    <span id = "pwdInfo"></span>
</p>



</body>
</html>

注意

  • html方法可以向指定的元素内部插入html语句, 用于动态修改网页

SpringMVC-AJAX

标签:service   主动权   bin   pre   public   test   pwd   验证   name   

原文地址:https://www.cnblogs.com/wang-sky/p/13651938.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!