首页 > 其他分享 >【WEEK4】 【DAY4】AJAX - Part One【English Version】

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

时间:2024-03-24 14:00:27浏览次数:21  
标签:function web 8.2 DAY4 server AJAX Part jQuery data

2024.3.21 Thursday

Contents

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

标签:function,web,8.2,DAY4,server,AJAX,Part,jQuery,data
From: https://blog.csdn.net/2401_83329143/article/details/136964699

相关文章

  • Linux C编程一站式学习 part2: C语言本质
    LinuxC编程一站式学习(akaedu.github.io)22.Makefile基础1.基本规则欲更新目标,必须首先更新它的所有条件;所有条件中只要有一个条件被更新了,目标也必须随之被更新。“更新”:执行一遍规则中的命令列表,命令列表中的每条命令必须以一个Tab开头对于Makefile中的每个以Tab开头......
  • Python编程—Ajax数据爬取
    Python编程—Ajax数据爬取​在浏览器中可以看到正常显示的页面数据,而使用requests得到的结果中并没有这些数据。这是因为requests获取的都是原始HTML文档,而浏览器中的页面是JavaScript处理数据后生成的结果,这些数据有多种来源:可能是通过Ajax加载的,可能是包含在HTML文档中......
  • CF1711B Party 题解
    CF1711BParty原题题意给定$n$个点带点权的无向图,点权$a_i$保证无重边自环,点权非负),要求删去一些点和它相连的边,使得剩下这个图的边数为偶数且删去点的点权之和最小。问删去点的点权之和最小是多少?分类讨论我们分类讨论一下。$m$为偶数,则不需要删边或点,直接输出$0$即......
  • 03天【代码随想录算法训练营34期】第二章 链表part01(203.移除链表元素 、707.设计链表
    203.移除链表元素竟然可以做个假head,学到了classListNode(object):def__init__(self,val=0,next=None):self.val=valself.next=nextclassSolution(object):defremoveElements(self,head,val):dummy_head=ListNode(-1)......
  • Ajax、JSON、响应式设计和Node.js
    Ajax、JSON、响应式设计和Node.js股票搜索(AJAX/JON/HTML5/Bootstrap/Angular/Node.js/CloudExercise)1.目标●熟悉AJAX和JSON技术●在客户端使用HTML5、Bootstrap和Angular的组合●在服务器端使用Node.js●熟悉Bootstrap,使用响应式设计增强用户体验●亲身体验云服务托......
  • LeetCode刷题记录——day4
    https://leetcode.cn/problems/trapping-rain-water/description/?envType=study-plan-v2&envId=top-interview-150对于一个可以构成“碗”的序列,最后装满水的话应该和最短的一边齐平,那么可以左右各遍历一次,记录每个元素位置对应的最短边高度,再对比就可以得出左右哪边最短class......
  • 戴尔windows服务器安装双系统报错For a UEFI installation, you must include an EFI
    安装centos7.9的分区时候,提示:ForaUEFIinstallation,youmustincludeanEFISystemPartitiononaGPT-formatteddisk,mountedat/boot/efi网上有好多人说修改bios,用常规的usb去启动,不要UEFI的方式,但我的windows系统已经是GPT格式,且原来就有一个EFI,所以我还是用UEFI的方......
  • PartA2
    PDF:《FromPointstoParts:3DObjectDetectionfromPointCloudwithPart-awareandPart-aggregationNetwork》CODE:https://github.com/sshaoshuai/PartA2-Nethttps://github.com/open-mmlab/OpenPCDet一、大体内容PartA2在PointRCNN基础上进行了扩展和改进,使得3D......
  • Vue学习笔记56--vue常用Ajax库(axios)
    vue常用Ajax库:1.vue-resource插件库npmivue-resource使用方式略,不建议使用,vue1.x使用广泛,官方已不维护2.axios通用的Ajax请求库,官方推荐,使用广泛axios在Vue项目中可以用来向后台发送请求(调接口API),获取响应信息的一个方法。Axios 是一个基于 promise 的 HTTP 库,可以......
  • Spark中driver、executor、job、stage、task、partition你懂吗?
        对于一个要提交到大数据集群的spark任务而言,准确说这个任务应该叫一个application,因为application是分布式任务,因此需要分配到多台机器中运行,而为了方便每个application的自我管理,这个多台机器中会有一台机器被选为小组长来管理整个application,而这个小组长的名字......