A Roadmap
  • Introduction
  • Roadmap
  • Basics
    • Basic Terminal Usage
      • Shell
        • 基本
        • 变量
        • 传递参数
        • 运算符
        • 命令
        • 流程控制
        • 函数
        • 输入输出重定向
    • Character Encoding
      • 字符编码
    • Data Structures & algorithms
    • Network
      • TCP/IP
      • Http/Https
        • 浏览器缓存
        • Status Code
        • GET & POST
        • HTTPS 握手过程
        • HostOnly Cookie
      • CDN
        • CDN 工作原理
    • Version Control
      • git message format
      • git commands
    • Principles
    • Design Patterns
    • Others
      • JSON
      • 正则表达式
  • Front End
    • Web Standard
      • Html
      • CSS
        • font-face 小记
        • Grid 布局简易笔记
      • Javascript
        • Ajax
          • Fetch
          • XMLHttpRequest
        • DOM
          • Selection
          • 常用 DOM 操作
          • script 标签的几个属性
        • Ecmascript
          • this 关键字
          • Event Loop
          • 隐式转换
          • Date
        • Event
          • 模拟事件
          • Others
    • Development
      • Package Management
        • npm
      • Modulization
        • 模块化机制
        • webpack 打包解析
      • Architecture
      • Build Tools
        • 如何编写一个自定义的 eslint 规则?
      • Debug
        • 移动端调试 web
      • Pre/Post Processors
      • Test
        • Jest Snapshot 使用指南
      • Type Checkers
        • TS 中 enum 的编译结果
    • Libs & frameworks
    • Platforms
      • Browser
        • Basics
          • 从输入 URL 到页面加载完成都发生了什么事情?
          • HTML 加载的过程示意图
          • 为什么读取某些属性,也会导致回流?
          • Chrome 进程模型
        • PWA
        • Compatible
        • Cross Origin
        • Performance
          • 性能检测:performance 对象
          • 性能指标
        • Others
          • 移动端 web 开发笔记
      • Server
      • Desktop Applications
      • Mobile Applications
        • Flutter 在移动端和 Web 端的技术实现
  • Back End
    • outline
    • Languages
      • Node
        • Event Loop
        • NodeJS 中的进程与线程
        • NodeJS 中的 esModule 与 commonJS
  • Clients
    • outline
    • 安装 IPA 包
  • DevOps
    • Languages
    • OS Concepts
    • Servers & terminal
  • UI & UX
    • outline
  • Others
    • Posts
      • 使用 node 爬取数据并导出到 excel
      • antd 1.x datepicker 时区问题
      • babel-transform-runtime 踩坑记录
      • lodash 按需加载注意事项
      • 记一次项目迁移的踩坑记录
      • 时区与JS中的Date对象
      • 记一次 vue + ts 开发踩坑
    • Tools
      • 个人常用的工具分享
      • tmux 简要笔记
Powered by GitBook
On this page
  • 创建对象
  • XMLHttpRequest 对象
  • 创建 XMLHttpRequest 对象
  • 发送请求
  • Properties
  • XHR 2.0

Was this helpful?

  1. Front End
  2. Web Standard
  3. Javascript
  4. Ajax

XMLHttpRequest

PreviousFetchNextDOM

Last updated 3 years ago

Was this helpful?

AJAX: Asynchronous JavaScript and XML

自己封装的一个简单的XMLHttpRequest库

创建对象

XMLHttpRequest 是 AJAX 的基础。

XMLHttpRequest 对象

所有现代浏览器均支持 XMLHttpRequest 对象(IE5 和 IE6 使用 ActiveXObject)。 XMLHttpRequest 用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

创建 XMLHttpRequest 对象

所有现代浏览器(IE7+、Firefox、Chrome、Safari 以及 Opera)均内建 XMLHttpRequest 对象。

创建语法:

variable = new XMLHttpRequest();

老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象:

variable = new ActiveXObject("Microsoft.XMLHTTP");

为了应对所有的现代浏览器,包括 IE5 和 IE6,请检查浏览器是否支持 XMLHttpRequest 对象。如果支持,则创建 XMLHttpRequest 对象。如果不支持,则创建 ActiveXObject :

var xmlhttp;
if (window.XMLHttpRequest) {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp = new XMLHttpRequest();
} else {
  // code for IE6, IE5
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

发送请求

方法

open

open(method, url, async)

  • method: "GET", "POST", "PUT", "DELETE", ...

  • url: "url"

  • async: true | false

GET

  • GET可以得到缓存结果

  • GET的长度是有限的(2048)

  • GET不够保密

  • 编码类型(ASIIC)

XHR.open( "GET" , "URL" , true );
XHR.send();

XHR.open( "GET" , "URL?name=value&name=value" , true );
XHR.send();

POST

  • 不会得到缓存结果

  • 可以发送大量数据

  • 足够安全

  • 编码类型(无限制,可包括二进制流)

XHR.open( "POST" , "URL" , true );
XHR.send();

XHR.oepn( "POST" , "URL" , true );
XHR.setRequestHeader(header , value);
XHR.send("name&value"); // request body

async

  • 异步时,不用等待服务器返回信息即可继续执行其他操作。需要设置服务器返回的信息为对应的状态时,应当执行的操作(onreadystatechange)

xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
  }
}
  • 同步时,需要等待服务器返回信息才能继续执行后面的脚本。设置为同步时,主线程会顺序执行xhr对象后面的语句,无法侦听readystatechange事件。

send

send(body)

body

  • A Document, in which case it is serialized before being sent.

  • A BodyInit, which as per the Fetch spec can be a Blob, BufferSource, FormData, URLSearchParams, ReadableStream, or USVString object.

note

  • 使用POST时,需要设置Content-Type为application/x-www-form-urlencoded

  • 如果send方法传入的不是字符串,则不需要设置header的Content-Type

Properties

  • responseText 获得字符串形式的响应数据

  • responseXML 获得字符串形式的响应数据

  • getResponseHeader 获取响应头,没有或不存在则返回null

  • getAllResponseHeaders

  • readystate

    • onreadystatechange 每次readystate发生改变时,即触发该事件

    • 取值

      • 0: 请求初始化,还没调用open()方法

      • 1: 服务器建立连接,还没调用send()方法

      • 2: 请求已经接受,已经调用send()方法,响应头和响应状态已经返回

      • 3: 请求处理中,下载中,已经得到部分响应实体

      • 4: 请求完成,响应就绪

  • status

  • statusText

XHR 2.0

  • 支持设置timeout

xhr.timeout = 2000; // time in milliseconds

xhr.onload = function () { // Request finished. Do processing here. };

xhr.ontimeout = function (e) { // XMLHttpRequest timed out. Do something here. };
  • 支持使用FormData

  • 支持CORS,需要后端配合。

    • withCredentials

xhr.withCredentials = true;
  • 可配置responseType - an enumerated value that returns the type of response

    • text

    • json

    • arrayBuffer

    • document

MDN
doris