【WEEK4】 【DAY4】AJAX - Part One【English Version】

2024.3.21 Thursday

8.AJAX

8.1. Introduction

  1. AJAX = Asynchronous JavaScript and XML.
  2. AJAX is a technique for updating parts of a web page without having to reload the entire page.
    Insert image description here
  3. Ajax is not a new programming language, but a technique for creating better, faster, and more interactive web applications.
  4. In 2005, Google made AJAX popular through its Google Suggest. Google Suggest can automatically complete your search words.
  5. 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.
  6. Just like the search box on Baidu in China!
  7. Traditional web pages (i.e., those not using AJAX) need to reload the entire page to update content or submit a form.
  8. Web pages using AJAX technology can achieve asynchronous partial updates with minimal data exchange with the backend server.
  9. 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

Insert image description here

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
Insert image description here

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

Insert image description here

8.2.3. Create applicationContext.xml

Insert image description here

<?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
Insert image description here

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

Insert image description here
Add lib support: Insert image description here

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

Insert image description here
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

  1. During registration, automatically check if the username already exists when entered.
  2. When logging in, prompt if the username or password is incorrect.
  3. 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

  1. 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!
  2. 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.
  3. jQuery offers several methods related to AJAX.
  4. 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.
  5. jQuery is not a producer but a natural porter. (jQuery is a library that contains a large number of JavaScript functions)
  6. 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

  1. Download address
    https://jquery.com/download/
    在这里插入图片描述

  2. 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:
Insert image description here

alert(data);

Insert image description here

alert(status);

Insert image description here

console.log("data="+data); 
console.log("data="+status);

Insert image description here
When entering characters that do not meet requirements:
Insert image description here
Insert image description here
Insert image description here

8.3.8. Process Diagram

Insert image description here
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

  • 68
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在第4周的可重复研究项目中,我将继续探索如何使用开放源代码工具和技术来实现可重复性和透明度。 首先,我将继续使用版本控制系统(如Git),以便跟踪我研究项目中的所有更改和改进。这将确保我能够回溯到每个版本的数据和代码,并对项目进行可重复性验证。在本周内,我还将学习更多关于Git分支和合并的知识,以便更好地组织和管理我的项目。 另外,我还将使用Jupyter Notebook来记录我的实验过程和结果。Jupyter Notebook提供了一个互动环境,可以将代码、文档和图形化结果结合在一起,使得我的研究成果更加易于理解和重现。我会确保我的Notebook中包含了所有必要的步骤和解释,以便他人能够准确地复现我的研究。 为了进一步提高可重复性,我还将采取一些数据预处理和清洗的措施。这些措施包括去除异常值、处理缺失数据和标准化数据等。我将确保我的数据处理过程明确记录,并提供相应的代码和文档,以便他人能够按照相同的步骤进行处理。 最后,我还计划使用容器化技术(如Docker)来实现我的研究项目的可移植性。通过将我的环境和依赖项封装在一个容器中,我可以确保其他人能够在不同的计算机和操作系统上轻松地运行我的代码和分析。 综上所述,第4周的可重复研究项目将继续探索一系列工具和技术,旨在提高我的研究项目的可重复性和透明度。通过使用版本控制系统、Jupyter Notebook、数据处理和清洗措施以及容器化技术,我将确保我的研究成果可以被其他人准确地重现和验证。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值