Spring Boot tutorial (7): Ajax

1. Introduction

Based on the needs of web projects, I will introduce the front-end and back-end interaction methods in web projects. The usually selected solution is to use Ajax technology to call the api interface provided by the back-end on the browser side to complete asynchronous requests and interactive updates of the page. Next, let's take a look at what Ajax is and how to use Ajax for functional development in the project.

AJAX = Asynchronous JavaScript and XML (asynchronous JavaScript and XML). It is a technology used to create fast and dynamic web pages. A small amount of data is exchanged between the browser and the server. Ajax can enable web pages to be updated asynchronously, which means that In the case of not reloading the entire webpage, a certain part of the webpage is updated. If the content of the traditional webpage needs to be updated, it must be jumped and reloaded.

Ajax technology makes the interaction between the website and the user more friendly. The more common functions implemented with Ajax technology include list pull up and load paging data, three-level linkage between provinces and cities, progress bar update, etc., all of which are through Ajax The technology can be completed on the current page, even if there is data interaction, it will not jump to the page, and the overall interaction effect has been greatly improved.

Second, the work process

Insert picture description here

The entire workflow of Ajax is shown in the figure above. When the user performs operations on the page, the js method is executed. In the js method, Ajax is used to asynchronously interact with the backend. First, the XMLHttpRequest object will be created. XMLHttpRequest is the basis of AJAX. After that, the parameters will be encapsulated in the request body or put in the request URL according to the page content, and then the request will be sent to the back-end server. After the request is successful, the data returned by the back-end will be parsed. And part of the logic processing, and finally partial updates to the page without refreshing the page.

Three, case

Create a new ajax-test.html under resources/static, the code is as follows:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Ajax 请求测试</title>
  </head>
  <body class="hold-transition login-page">
    <div style="width:720px;margin:7% auto">
      <div class="content">
        <div class="container-fluid">
          <div class="row">
            <div class="col-lg-6">
              <div class="card">
                <div class="card-header">
                  <h5 class="m-0">接口测试1</h5>
                </div>
                <div class="card-body">
                  <input
                    type="text"
                    id="info"
                    class="form-control"
                    placeholder="请输入info值"
                  />
                  <h6 class="card-title">接口1返回数据如下:</h6>
                  <p class="card-text" id="test1"></p>
                  <a href="#" class="btn btn-primary" onclick="requestTest1()"
                    >发送请求1</a
                  >
                </div>
              </div>
              <br />
              <div class="card card-primary card-outline">
                <div class="card-header">
                  <h5 class="m-0">接口测试2</h5>
                </div>
                <div class="card-body">
                  <h6 class="card-title">接口2返回数据如下:</h6>
                  <p class="card-text" id="test2"></p>
                  <a href="#" class="btn btn-primary" onclick="requestTest2()"
                    >发送请求2</a
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

Two buttons are defined on the ajax-test page. When clicked, the onclick click event is triggered respectively, and the partial update of the page content is performed in the implementation logic of the click event.

Because the native Ajax implementation is relatively cumbersome, the actual development generally uses the Ajax method encapsulated by jQuery, or the Ajax method encapsulated by other libraries. For details, please refer to the jQuery ajax explanation.

Before calling, first introduce the jQuery library in the html code, and then define two event-triggered js methods according to the click event: requestTest1() and requestTest2(). In the methods, Ajax is used to send the request to the backend. After the request is successful Assign the response result to the corresponding div, the code is as follows:

<!-- 这部分放在html的head标签中 -->
<!-- 引入jQuery -->
<script src="https://cdn.staticfile.org/jquery/1.12.0/jquery.min.js"></script>

<!-- 定义两个点击事件并实现 Ajax 调用逻辑 -->
<script type="text/javascript">
  function requestTest1() {
    
    
    var info = $('#info').val();
    $.ajax({
    
    
      type: 'GET', //方法类型
      dataType: 'text', //预期服务器返回的数据类型
      url: 'api/test1?info=' + info, //请求地址
      contentType: 'application/json; charset=utf-8',
      success: function (result) {
    
    
        //请求成功后回调
        $('#test1').html(JSON.stringify(result));
      },
      error: function () {
    
    
        //请求失败后回调
        $('#test1').html('接口异常,请联系管理员!');
      },
    });
  }
  function requestTest2() {
    
    
    $.ajax({
    
    
      type: 'GET', //方法类型
      dataType: 'json', //预期服务器返回的数据类型
      url: 'api/test2',
      contentType: 'application/json; charset=utf-8',
      success: function (result) {
    
    
        $('#test2').html(JSON.stringify(result));
      },
      error: function () {
    
    
        $('#test2').html('接口异常,请联系管理员!');
      },
    });
  }
</script>

Method one will first get the field entered by the user in the input box, then splice it into the requested URL, and finally send an Ajax request and complete the callback. Method two is similar, when the user clicks the button to send the request, onclick will be triggered Click on the event and call the requestTest2() method, enter the success callback method after the request is completed, and display the content of the request result in the div.

Create a new RequestTestController under the package com.wang.controller, the code is as follows:

package com.wang.controller;

import com.wang.entity.Author;
import com.wang.util.StringTool;//我本人定义的一个工具类
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api")
public class RequestTestController {
    
    
        @RequestMapping(value = "/test1", method = RequestMethod.GET)
        public String test1(String info) {
    
    
            if (!StringTool.isNotBlank(info)) {
    
    
                return "请输入info的值!";
            }
            return "你输入的内容是:" + info;
        }
        @RequestMapping(value = "/test2", method = RequestMethod.GET)
        public List<Author> test2() {
    
    
            List<Author> list = new ArrayList<>();
            Author author1 = new Author("test1-id","test1-name","test1-pass","test1-mail");
            Author author2 = new Author("test2-id","test2-name","test2-pass","test2-mail");
            list.add(author1);
            list.add(author2);
            return list;
        }
}

The controller implements two methods and sets the request address mapping to process the asynchronous request sent by the front end. The test1() method will return a string to the front end according to the value of the info field passed in by the front end. The request method is GET, test2( ) Method will return a collection object to the front end, the request method is GET.

When connecting the front and back ends, you need to determine the request path, request method, return result format, etc. For example, the request method defined by the back end is GET, then the type must be set to GET when setting up Ajax, otherwise the request cannot be initiated normally. The format of the results returned in the test1() method and the test2() method is also different, so you also need to pay attention to the dataType when making Ajax calls on the front end. For example, in this case, the string type and the collection type are returned respectively, so it is required in the Ajax request Set the dataType to text and json respectively, otherwise the front end will directly enter the error callback after the Ajax call, instead of the success callback.

Start the service, then visit the html page in the browser, and test:

Insert picture description here

The front-end uses Ajax technology to call the back-end interface and update the functional test of the front-end page content.

Guess you like

Origin blog.csdn.net/Tracycoder/article/details/113944435