XMLHttpRequest实现异步请求

发布时间 2023-04-20 22:00:19作者: 突破铁皮

XMLHttpRequest基本概念

XMLHttpRequest是一种用于在Web浏览器和服务器之间进行异步数据交换的技术。它可以在不重新加载页面的情况下向服务器发送HTTP请求,接收和处理来自服务器的响应,并更新网页的部分内容。XMLHttpRequest也被称为XHR,它是一种在Web开发中常用的JavaScript API。

XMLHttpRequest属性:

  • onreadystatechange:每次readyState属性改变时会调用的事件处理函数。
  • readyState:表示XMLHttpRequest对象的请求状态,共有5种状态值,分别是0-未初始化,1-正在加载,2-已加载,3-交互中,4-完成。
  • response:返回的响应数据。根据responseType的不同,可能返回不同类型的数据,例如字符串、XML文档、JSON数据、Blob对象或者ArrayBuffer对象。
  • responseType:设置响应数据类型的属性,可选值为"""arraybuffer""blob""document""json""text"
  • responseText:返回响应数据的文本内容,如果响应类型不是"text/plain"或者"text/html",则返回null。
  • responseURL:响应数据的URL。
  • responseXML:返回的XML DOM对象,如果响应数据不是XML格式,则返回null。
  • status:响应的HTTP状态码。
  • statusText:响应的HTTP状态文本信息。
  • timeout:请求的超时时间,单位为毫秒,默认为0,表示没有超时时间限制。
  • withCredentials:表示是否允许跨域请求发送Cookie等身份凭证,可选值为true和false。

XMLHttpRequest方法:

  • abort():中止当前请求。
  • getAllResponseHeaders():返回所有响应头信息。
  • getResponseHeader():返回指定名称的响应头信息。
  • open():初始化请求参数,并准备发送请求。
  • send():发送请求。
  • setRequestHeader():设置请求头信息。

代码实例

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<form action="/test" method="post" id="myForm">
    <input type="text" name="id">
    <br/>
    <input type="text"  name="pwd">
    <br/>
    <button type="submit">提交</button>
</form>
</body>
</html>
<script>
    let myForm=document.getElementById('myForm')
    let xhr=new XMLHttpRequest()
    myForm.addEventListener("submit",function (event) {
        event.preventDefault();//阻止自动提交
        let data=new FormData(this)
        xhr.open("POST","/test",true)
        xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
        xhr.onload=function (){
            if(xhr.status==200){
                alert(xhr.response)
            }
            else alert('提交错误')
        }
        xhr.send(new URLSearchParams(data))
    })
</script>
package com.example.learn.controller;

import lombok.SneakyThrows;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class AllController {
    @ResponseBody
    @SneakyThrows
    @RequestMapping("/test")
    public  String test(String id,String pwd){
        String res="登录失败";
        if(id.equals("123")&&pwd.equals("123")) res="登录成功";
        return res;
    }

}