以SpringBoot作为后台实践ajax异步刷新

1.什么是ajax

1.Ajax全称:Asynchronous JavaScript And XML

2.是一种异步加载数据的技术

3.可以通过使用Ajax,实现页面的局部刷新

简单来讲就是通过ajax,你不需要重新刷新整个页面就能实现对局部页面的刷新操作。

2.AJAX的使用

使用ajax主要有以下四步骤

//1.创建ajax对象
var xhr=new XMLHttpRequest();
2.监听ajax对象
xhr.onreadystatechange=function(){}
3.打开对象
xhr.open()
4.发送请求
xhr.send()

ajax有get和post两种方式发送请求,下面通过java和ajax模拟异步刷新。java方面以SpringBoot作为后台。

3.SpringBoot后台的搭建

搭建SpringBoot后台不是一件困难的事情,下图是整个项目的结构图

3.1 创建项目,引入依赖

创建maven项目,引入SpringBoot相关的依赖

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sdxb</groupId>
    <artifactId>ajaxtest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

3.2 编写启动类和配置文件

编写SpringBoot的启动类AjaxtextApplication

@SpringBootApplication
public class AjaxtestApplication {
    public static void main(String[] args) {
        SpringApplication.run(AjaxtestApplication.class);
    }
}

所有html代码均放在resource文件夹下的templates中,在application.properties文件中表明静态文件路径

spring.resources.static-locations=classpath:/templates/
spring.mvc.view.suffix=.html

3.3 编写controller

新建indexController,首先写一个简单的方法,用于返回我们第一个静态页面index.html

@Controller
public class indexController {
    @RequestMapping("/test")
    public String index(){
        return "index";
    }
}

至此,一个简单的java后台就搭完了。

4.ajax的get请求

我们写一个简单的页面,只包含一个按钮和一行文本。然后通过ajax的get请求去后端请求一段数据,不断刷新到文本处。下面是html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<input type="button" id="btn" value="button">
<h1>test</h1>
<script type="text/javascript">
    var btn=document.getElementById("btn");
    btn.onclick=function () {
        //1.创建ajax对象
        var xhr=new XMLHttpRequest();
        //2.监听ajax对象
        xhr.onreadystatechange=function () {
            /*
            /当xhr对象的readystate属性发生了改变,这个事件就会触发
            readyState:
            0 ===>xhr对象已经创建,但是还没有进行初始化操作
            1===>xhr对象已经调用了open
            2===)xhr已经发出ajax请求
            3 ===>已经返回了部分数据
            4===>数据已经全部返回
            */
            if (xhr.readyState!=4){
                return;
            }
            //如果请求没有出错则会返回200-300的状态码
            if (xhr.status>=200&&xhr.status<=300){
                document.getElementsByTagName("h1")[0].innerHTML+=xhr.responseText;
            }
        }
        //3.打开对象,第三个参数表示是否使用异步
        xhr.open("get","http://localhost:8080/test2",true);
        //4.发送请求
        xhr.send();
    }
</script>
</body>
</html>

关键的ajax代码处已经用注解标出。还需要在controller中处理http://localhost:8080/test2的请求,在indexController中添加以下代码:

@GetMapping("/test2")
@ResponseBody
public String index2(HttpServletResponse response){
    return "hello world";
}

运行项目,输入http://localhost:8080/test,不断点击按钮,不断将文本刷新到页面上:

5.ajax的post请求

通常需要提交数据的场景都会使用post请求,通过表单提交数据,因此就来模拟登陆的场景。为了方便,我直接将用户名和密码写在前端代码中:login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<input type="button" id="btn" value="button">
<h1>test</h1>
<script type="text/javascript">
    var btn=document.getElementById("btn");
    btn.onclick=function () {
        //1.创建ajax对象
        var xhr=new XMLHttpRequest();
        //2.监听ajax对象
        xhr.onreadystatechange=function () {
            /*
            /当xhr对象的readystate属性发生了改变,这个事件就会触发
            readyState:
            0 ===>xhr对象已经创建,但是还没有进行初始化操作
            1===>xhr对象已经调用了open
            2===)xhr已经发出ajax请求
            3 ===>已经返回了部分数据
            4===>数据已经全部返回
            */
            if (xhr.readyState!=4){
                return;
            }
            if (xhr.status>=200&&xhr.status<=300){
                //处理后端传送的json对象
                var result=JSON.parse(xhr.responseText)
                if (result.res==true){
                    document.getElementsByTagName("h1")[0].innerHTML="登陆成功";
                } else {
                    document.getElementsByTagName("h1")[0].innerHTML="登陆失败";
                }
            }
        }
        //3.打开对象
        xhr.open("post","http://localhost:8080/test3",true);
        //使用post请求需要为xhr对象添加请求头部
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        //4.发送请求,数据写在参数中
        xhr.send("username=sdxb&password=123456");
    }
</script>
</body>
</html>

同样在indexController中再写两个方法:

@RequestMapping("/log")
public String login(){
    return "login";
}
@PostMapping("/test3")
@ResponseBody
public Result index3(HttpServletRequest request,HttpServletResponse response){
    String username=request.getParameter("username");
    String password=request.getParameter("password");
    Result result=new Result();
    if (username.equals("sdxb")&&password.equals("123456")){
        result.setRes(true);
        return result;
    }
    else {
        result.setRes(false);
        return result;
    }
}

这里的Result对象是自己写的类,只包含一个Res对象,当使用了@ResponseBody后,返回对象时会自动转化成json对象传递给前端。

 附上github代码:https://github.com/OliverLiy/springbootANDajax

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章