2024.3.21 Thursday
Contents
- 8.AJAX
- 8.1. Introduction
- 8.2. Simulating ajax
- 8.3. jQuery.ajax
8.AJAX
8.1. Introduction
- AJAX = Asynchronous JavaScript and XML.
- AJAX is a technique for updating parts of a web page without having to reload the entire page.
- Ajax is not a new programming language, but a technique for creating better, faster, and more interactive web applications.
- In 2005, Google made AJAX popular through its Google Suggest. Google Suggest can automatically complete your search words.
- Google Suggest uses AJAX to create a highly dynamic web interface: when you type keywords into Google’s search box, JavaScript sends these characters to the server, and then the server returns a list of search suggestions.
- Just like the search box on Baidu in China!
- Traditional web pages (i.e., those not using AJAX) need to reload the entire page to update content or submit a form.
- Web pages using AJAX technology can achieve asynchronous partial updates with minimal data exchange with the backend server.
- With AJAX, users can create direct, highly available, richer, and more dynamic web user interfaces similar to native desktop applications.
8.2. Simulating ajax
8.2.1. Create a new module: springmvc-06-ajax
8.2.2. Add web support, import pom dependencies
Since this module is created under the SpringMVC_try1 directory, it can directly use the dependencies of the parent file
8.2.2.1. Modify web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--Bind configuration file-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<!--Startup loading-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param> <!--Solve garbled text-->
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern> <!--Filter all requests-->
</filter-mapping>
</web-app>
8.2.2.2. Create a jsp folder
8.2.3. Create applicationContext.xml
<?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">
<!-- Automatically scan specified packages, all annotated classes managed by the IOC container -->
<context:component-scan base-package="P24.controller"/>
<mvc:annotation-driven/>
<!-- View Resolver -->
<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>
8.2.4. Create AjaxController.java
First, create a controller folder
package P24.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AjaxController {
@RequestMapping("/t1")
public String test(){
return "hello";
}
}
For testing purposes
8.2.5. Configure Tomcat
Add lib support:
8.2.6. Note
If a module is deleted and then recreated with the same name, you may encounter the “Module ‘----’ already exists” error (after deleting files in the project save folder). For solutions, see https://blog.csdn.net/weixin_43673163/article/details/126538827
8.2.7. Create test.html
Note the creation location, which is at the same level as WEB-INF and directly under the web directory
Test: Loaded a window with a height of 500px
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>iframe Test Experience Page Without Refresh</title>
<script>
function go() {
var url1 = document.getElementById("url").value;
// Get all variable values in advance
document.getElementById("iframe1").src=url1;
}
</script>
</head>
<body>
<div>
<p>Please enter the address:</p>
<p>
<input type="text" id="url" value="https://www.csdn.net/">
<input type="button" value="Submit" onclick="go()">
</p>
</div>
<!--Popup window-->
<div>
<iframe id="iframe1" style="width: 100%; height: 500px"></iframe>
</div>
</body>
</html>
- Create ajax-frame.html (same effect)
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>kuangshen</title>
</head>
<body>
<script type="text/javascript">
// window.onload = function(){
// var myDate = new Date();
// document.getElementById('currentTime').innerText = myDate.getTime();
// };
function LoadPage(){
var targetUrl = document.getElementById('url').value;
console.log(targetUrl);
document.getElementById("iframePosition").src = targetUrl;
}
</script>
<div>
<p>Please enter the address to load: <span id="currentTime"></span></p>
<p>
<!-- <input id="url" type="text" value="https://www.baidu.com/">Do not use Baidu's website, it can't be opened-->
<input id="url" type="text" value="https://www.csdn.net/"/>
<input type="button" value="Submit" onclick="LoadPage()">
</p>
</div>
<div>
<h3>Loading Page Position:</h3>
<iframe id="iframePosition" style="width: 100%;height: 500px;"></iframe>
</div>
</body>
</html>
Note: The official website of Baidu cannot be accessed in the input box, you can use the URL of Baidu Zhidao for practice.
8.2.8. What can be done with Ajax
- During registration, automatically check if the username already exists when entered.
- When logging in, prompt if the username or password is incorrect.
- When deleting a data row, send the row ID to the backend. After the database successfully deletes it, also remove the data row from the page DOM.
And so on.
8.3. jQuery.ajax
8.3.1. Introduction
- We will not discuss the pure JS native implementation of Ajax here, but instead use the jQuery provided, which is convenient for learning and use, to avoid reinventing the wheel. Interested students can learn about the native JavaScript XMLHttpRequest!
- The core of Ajax is the XMLHttpRequest object (XHR). XHR provides interfaces for sending requests to the server and parsing server responses. It can obtain new data from the server in an asynchronous way.
- jQuery offers several methods related to AJAX.
- With jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using HTTP Get and HTTP Post - and you can load these external data directly into selected elements of the webpage.
- jQuery is not a producer but a natural porter. (jQuery is a library that contains a large number of JavaScript functions)
- The essence of jQuery Ajax is XMLHttpRequest, which is encapsulated for easy calling!
8.3.2. Some parameters of jQuery.ajax(…)
url: Request address
type: Request method, GET, POST (use method after 1.9.0)
headers: Request headers
data: Data to send
contentType: Content type to be sent to the server (default: “application/x-www-form-urlencoded; charset=UTF-8”)
async: Whether it is asynchronous
timeout: Set request timeout time (milliseconds)
beforeSend: Function to execute before sending the request (global)
complete: Callback function after completion (global)
success: Callback function after success (global)
error: Callback function after failure (global)
accepts: Tells the server what data types the client can accept through the request header
dataType: Converts the data returned by the server into a specified type
“xml”: Converts the content returned by the server into xml format
“text”: Converts the content returned by the server into plain text format
“html”: Converts the content returned by the server into plain text format. When inserted into the DOM, if it contains JavaScript tags, it will attempt to execute them.
“script”: Tries to execute the return value as JavaScript, then converts the content returned by the server into plain text format
“json”: Converts the content returned by the server into a corresponding JavaScript object
“jsonp”: In JSONP format, when calling functions in the form of “myurl?callback=?”, jQuery will automatically replace ? with the correct function name to execute the callback function.
8.3.3. Importing jQuery
-
Download address
https://jquery.com/download/
-
Import steps
Right-click the link in the figure above and save it to the local address, then import it as shown in the figure below (web-statics-js).
8.3.4. Modifying applicationContext.xml
<?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">
<!-- Automatically scan the specified package, all annotation classes are managed by the IOC container below -->
<context:component-scan base-package="P24.controller"/>
<!-- Static resource filtering -->
<mvc:default-servlet-handler />
<mvc:annotation-driven/>
<!-- View Resolver -->
<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>
8.3.5. Modifying index.xml
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
Continuing with the translation into English:
```xml
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<%--<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>--%>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.7.1.js"></script>
<script>
<%--Event a--%>
function a1(){
$.post({
//1. Request address
url:"${pageContext.request.contextPath}/a1",
//2. Request data
//$("#txtName").val() extracts the value given in the input box, here 'name' is the String name in the method a1 of AjaxController
data:{'name':$("#txtName").val()},
//3. On success
success:function (data,status) {
//Popup display
alert(data);
alert(status);
//Display in console interface
console.log("data="+data);
console.log("data="+status);
},
// //4. On error
// error:function () {
// }
});
}
</script>
</head>
<body>
<%--onblur: Event triggered on focus loss--%>
<%--When losing focus, send a request (with information) to the backend--%>
<%-- <a href="/t1"></a>This cannot achieve the focus loss function—because it will directly redirect or forward--%>
Username:<input type="text" id="txtName" onblur="a1()"/>
</body>
</html>
8.3.6. Modifying AjaxController.java
package P24.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 ("zzz".equals(name)){
response.getWriter().print("true");
}else {
response.getWriter().print("false");
}
}
}
8.3.7. Running
After entering any content in the input box, if it loses focus, it will trigger the function a1, which sends the data to the backend’s a method as the name parameter. After judgment, it will pop up “true” or “false”.
http://localhost:8080/springmvc_06_ajax_war_exploded/
Entering characters:
alert(data);
alert(status);
console.log("data="+data);
console.log("data="+status);
When entering characters that do not meet requirements:
8.3.8. Process Diagram
Points to note when learning frontend
Html+css+js (proficient)
Js
includes: 1Functions (closure is a must-test, which means calling itself), 2Dom (id, name, tag; create, remove), 3Bom (window events: operating the browser; document: manipulating the document object)
ES6
: import, require