7. Ajax research [notes]

Posted by umol on Thu, 27 Jan 2022 13:29:41 +0100

Ajax research

brief introduction

  • AJAX = Asynchronous JavaScript and XML.

  • AJAX is a technology that can update some web pages without reloading the whole web page.

  • Ajax is not a new programming language, but a technology for creating better, faster and more interactive Web applications.

  • In 2005, Google made AJAX popular through its Google suggest. Google Suggest can automatically help you search for words.

  • Google Suggest uses AJAX to create a highly dynamic web interface: when you enter keywords in Google's search box, JavaScript will send these characters to the server, and then the server will return a list of search suggestions.

  • Just like the domestic Baidu search box!

  • Traditional web pages (that is, web pages without ajax Technology) need to reload the whole web page if they want to update the content or submit a form.

  • Web pages using ajax technology can realize asynchronous local update through a small amount of data exchange in the background server.

  • Using Ajax, users can create a direct, highly available, richer and more dynamic Web user interface close to local desktop applications.

  • By using xhr to send and receive data instead of the browser, you can modify the local page, that is, the page does not need to be refreshed

  • The bottom layer of ajax is XMLHttpRequest

AJAX can be used to:

  • When registering, enter the user name to automatically detect whether the user already exists.
  • When logging in, you will be prompted with the wrong user name and password
  • When deleting a data row, the row ID is sent to the background, and the background deletes it in the database. After the database is deleted successfully, the data row is also deleted in the page DOM.
  • ... wait

jQuery.ajax

Directly use the provided by jquery to facilitate learning and use and avoid repeated wheel building.

  • The core of Ajax is the XMLHttpRequest object (XHR).

  • XHR provides an interface for sending requests to the server and parsing server responses.

  • It can obtain new data from the server asynchronously.

  • jQuery provides several AJAX related methods.

  • Through the jQuery AJAX method, you can use HTTP Get and HTTP Post to request text, HTML, XML or JSON from a remote server - and you can load these external data directly into the selected elements of the web page.

  • jQuery is not a producer, but a nature porter.

  • The essence of jQuery Ajax is XMLHttpRequest, which is encapsulated and easy to call!

jQuery.ajax(...)
      Some parameters:
            url: Request address
            type: Request method, GET,POST(1.9.0 Later use method)
        headers: Request header
            data: Data to send
    contentType: The content encoding type of the message to be sent to the server(default: "application/x-www-form-urlencoded; charset=UTF-8")
          async: Asynchronous
        timeout: Set request timeout (MS)
      beforeSend: Function executed before sending the request(overall situation)
        complete: Callback function executed after completion(overall situation)
        success: Callback function executed after success(overall situation)
          error: Callback function executed after failure(overall situation)
        accepts: Send the request to the server and tell the server the data type acceptable to the current client
        dataType: Converts the data returned by the server to the specified type
          "xml": Convert the content returned by the server into xml format
          "text": Convert the content returned by the server into normal text format
          "html": Convert the content returned by the server into normal text format and insert DOM If it contains JavaScript Tag, it will try to execute.
        "script": Try to treat the return value as JavaScript To execute, and then convert the content returned by the server into normal text format
          "json": Convert the content returned by the server into the corresponding JavaScript object
        "jsonp": JSONP Format usage JSONP When calling a function in the form, such as "myurl?callback=?" jQuery Will automatically replace ? Enter the correct function name to execute the callback function
 The type of content encoding that will send the message to the server(default: "application/x-www-form-urlencoded; charset=UTF-8")
          async: Asynchronous
        timeout: Set request timeout (MS)
      be

For a simple test, use the most primitive HttpServletResponse processing, which is the simplest and most common

1. Configure web XML and spring MVC configuration files, just copy the above case [remember static resource filtering and annotation driven configuration]

<?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">

    <!--    springmvc Main configuration-->
    
    <!--    1.Scan the package to make the annotations under the specified package effective,from IOC Unified container management    Find the controller class through this line of code-->
    <context:component-scan base-package="com.q.controller"/>

    <!--    2.Annotation driven is to omit 1.Processor mapper and 2.Processor adapter 3.solve json Garbled code problem-->
    <mvc:annotation-driven>

        <mvc:message-converters register-defaults="true">
            <!--solve json Garbled code problem-->
            <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>

    <!-- 3.Give Way Spring MVC Do not process static resources, for example: css js html mp3 mp4 -->
    <mvc:default-servlet-handler/>

  
    <!--    4.view resolver  internalResourceViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <!--prefix-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--suffix-->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

2. Write an Ajax controller

@RequestMapping("/a1")
    public void ajax1(String name, HttpServletResponse response) throws IOException {
        if ("admin".equals(name)) {
            response.getWriter().print("true");
        } else {
            response.getWriter().print("false");
        }
    }

3. To import jquery, you can use the online CDN or download the import

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="${pageContext.request.contextPath}/js/jquery-3.1.1.min.js"></script>

4. Write index JSP test

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>$Title$</title>
    
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <%--        <script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>--%>
    
    <script>
        function a1() {
            var name = $("#txtName").val();
            $.post({
                url: "${pageContext.request.contextPath}/a1",
                data: {'name': name},
                success: function (data, status) {
                    alert(data);
                    alert(status)
                }
            });
        }
    </script>
</head>
<body>

<%--onblur: Event triggered by loss of focus--%>
<label for="txtName">user name: </label><input type="text" id="txtName" οnblur="a1()"/>
</body>
</html>

5. Start tomcat test! Open the browser console. When we leave the input box with the mouse, we can see that an ajax request has been issued! It is the result returned to us by the background! Test successful!

Spring MVC implementation

Entity class user

package com.q.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;

}

Let's get a collection object and show it to the front page

@RequestMapping("/toa2")
    public String ajaxto02() {
        return "test";
    }

    @RequestMapping("/a2")
    @ResponseBody
    public List<User> ajax2() {
        List<User> list = new ArrayList<User>();

        list.add(new User("ljq0", 3, "male"));
        list.add(new User("ljq1", 3, "male"));
        list.add(new User("ljq2", 3, "male"));
        return list; //Due to the @ ResponseBody annotation, convert the list to json format and return
    }

Front page

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

<input type="button" id="btn" value="get data"/>
<table width="80%" align="center">
    <tr>
        <td>full name</td>
        <td>Age</td>
        <td>Gender</td>
    </tr>
    <tbody id="content">
    </tbody>
</table>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<%--<script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>--%>
    
<script>
    <%--Entry function-->
    $(function () {
        //Click the button to trigger the behavior
        $("#btn").click(function () {
            //Use the get method to call the corresponding link,
            $.get("${pageContext.request.contextPath}/a2",
                function (data) {
                    console.log(data)
                    //    Define a variable to store our data format
                    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>
</html>

Output:

Registration prompt effect

Then test a small Demo and think about how to do the real-time prompt behind the input box when registering at ordinary times; How to optimize

Write a Controller

  @RequestMapping("/toa3")    public String ajaxto03() {        return "login";    }    @RequestMapping("/a3")    @ResponseBody    public String ajax3(String name, String pwd) {        String msg = "";        //There is data in the simulation database if (name! = null) {if ("admin". Equals (name)) {MSG = "OK";} Else {MSG = "user name input error";}} if (pwd != null) {            if ("123456".equals(pwd)) {                msg = "OK";            }  Else {MSG = "incorrect password input";}} return msg; // Due to the @ ResponseBody annotation, convert MSG into json format and return}

Front page login jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>Sign in</title>    <%-- It's easy to have problems here. We need to add type Type, otherwise it will report an error and cannot be found jquery--%>    <script type="text/javascript" src="https://code. jquery. com/jquery-3.1.1. min.js"></script>    <%--    <script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1. Min.js "> < / script > -- >% > < script > function a1() {var name = $(" #name "). Val(); VAR name1 = {" name ": name}; $. Post ({/ / trigger this function and start to jump to the following address to find the data URL:" ${pagecontext. Request. Contextpath} / A3 ", / / this # number is very important. Otherwise, you can't find the data. Find the data and put it in it. / / data: {name ': $(" #name "). Val()}, data: name1, / / judge on success and output the relevant content success: function (data) {if (data. Tostring() = = =' OK ') {                        $("#userInfo").css("color", "green");                    }  else {                        $("#userInfo").css("color", "red");                    }                    $ ("#userInfo"). html(data);// Output information}});} function a2() {            var pwd = $("#pwd").val();            var pwd1 = {"pwd": pwd};            $. Post ({/ / 1. Find the address of the transaction judgment first, return the relevant data url: "${pageContext.request.contextPath}/a3", / / 2, get the data / / data: {'PWD': $("#pwd"). Val()}, data: pwd1, / / 3, judge after obtaining the information successfully, Output relevant information success: function (data) {if (data. Tostring() = = 'OK') {$("#pwdinfo")} else {$("#pwdinfo"). CSS ("color", "red"); / / set the style} $("#pwdinfo") html(data);// Output the judged result}});}</ Script > < / head > < body > < p > < label for = "name" > User Name: < / label > < input type = "text" id = "name" ο Nblur = "a1()" / > < span id = "userinfo" > < / span > < / P > < label for = "PWD" > password: < / label > < input type = "text" id = "PWD" ο Nblur = "a2()" / > < span id = "pwdinfo" > < / span > <% -- the information we defined --% ></p></body></html>

**[remember to deal with json garbled code] * * configure in mvc configuration file

Test the effect, dynamic request response, local refresh, that's it!

Pay attention to error reporting:

  1. There is an error when referencing jquery. It is not referenced because the type is not set. This error is very serious and the data cannot be obtained directly
  2. If ajax omits # no data when referring to the data id, there will be no data;

Topics: Java Ajax Spring MVC