XMLHttpRequest 与 Ajax 概要
关于XMLHttpRequest
开发者使用XMLHttpRequest对象与服务端进行交互(发送http请求、接受返回数据等),可以在不打断用户下一步操作的情况下刷新局部页面。XMLHttpRequest在Ajax中被大量使用。
XMLHttpRequest被应用时的处理机制

(图片来源:developer.mozilla.org)
关于Ajax
Ajax(切勿读为汉语化的“阿贾克斯”,应读英音/ˈeɪˌdʒæks/--“A寨科泗”。。)全称:Asynchronous JavaScript And XML (异步的JavaScript和XML)。
Ajax不仅可以只更新页面中的部分DOM,而且工作流程是异步的,不会阻塞其后面代码的正常执行。
在现代Web标准和实际应用中,Ajax正在逐步地被一些JavaScript框架封装好的方法和官方新的 Fetch API 所替代。
在正式介绍Ajax的使用前,我们认识下IE中的一个与XMLHttpRequest对象相应的概念(尽管后续它不会再被提及):
var ajax = new ActiveXObject('Microsoft.XMLHTTP');
深入了解XMLHttpRequest
// xhr对象的构造函数,用来实例化一个xhr对象。
XMLHttpRequest()
// xhr的常用属性 /* 1. onreadystatechange属性将指向一个事件处理函数,当xhr的readyState属性发生变化时被触发 */
xhr.onreadystatechange
// usage:
xhr.onreadystatechange = callback; /* 2. --ReadOnly-- readyState属性将返回当前请求的状态 */
xhr.readyState // usage:
const xhr = new XMLHttpRequest();
console.log('UNSENT', xhr.readyState); // readyState will be 0 xhr.open('GET', '/api', true);
console.log('OPENED', xhr.readyState); // readyState will be 1 xhr.onprogress = function () {
console.log('LOADING', xhr.readyState); // readyState will be 3
}; xhr.onload = function () {
console.log('DONE', xhr.readyState); // readyState will be 4
}; xhr.send(); // 具体示意如下图(插播一条广告):

/* 3. 获取或设置responseType(符合XMLHttpRequestResponseType规范的字符串) */
xhr.responseType // usage:
const resType = xhr.responseType;
// or
xhr.responseType = 'json'; // XMLHttpRequestResponseType具体如下(插播第二条广告):

/* 4. --ReadOnly-- response返回响应体所包含的内容,内容格式由responseType决定 */
xhr.response // usage:
const result = xhr.response; // 注:在responseType为''或者'text'时,response 和 responseText 可以相互替用 /* 5. --ReadOnly-- status属性将返回数字类型的http状态码 */
xhr.status // usage:
const status = xhr.status; /* 6. --ReadOnly-- statusText将返回响应状态的文本描述,分别有''、'OK'、'Not Found' */
xhr.statusText // usage:
const statusText = xhr.statusText; /* 7. timeout属性将指定请求自动终止的毫秒数,默认为零,即没有超时设置 */
xhr.timeout // usage:
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api', true); xhr.timeout = 5000; xhr.onload = function () { // Request finished. }; xhr.ontimeout = function (e) {
// when XMLHttpRequest timed out ...
}; xhr.send();
// xhr 的常用方法 /* 1. open 方法将创建一个新的http请求或者重新发送一个已有请求 */
xhr.open(method, url [, async, username, password]) // usage:
xhr.open('GET', '/api'); /* 2. send 方法将向服务器发送一个请求 */
xhr.send(body) // usage:
xhr.send(); /* 3. abort 方法将退出一个已有请求 */
xhr.abort() // usage:
xhr.abort(); /* 4. XMLHttpRequestEventTarget.onload (注:不是xhr的方法,而是事件)*/
xhr.onload // usage:
xhr.onload = callback; /* 5. setRequestHeader 可以设置一个http请求头的值 */
xhr.setRequestHeader(headername, value) // usage:
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { //... }; xhr.send("foo=bar&lorem=ipsum");
实际编程中Ajax和XMLHttpRequest的应用
// 简单示例
const XHR = new XMLHttpRequest();
const handleReadyStateChange = () => {
try {
if (XHR.readyState === XHR.DONE) {
if (XHR.status === 200) {
console.log(XHR.response);
} else {
throw new Error('request failed!');
}
}
} catch (ex) {
console.error('Caught Exception: ' + ex.message);
}
}; function generateRequest(type, api, body = null) {
if (!XHR) {
console.error('Cannot find XMLHttpRequest object!');
return false;
} XHR.onreadystatechange = handleReadyStateChange;
XHR.open(type, api);
XHR.send(body);
}
-- 待续
XMLHttpRequest 与 Ajax 概要的更多相关文章
- Ajax概要:
Ajax概要: Ajax不是个全新的技术,它是多种技术合并在一起产生的,包括XHTML,CSS,JavaScript,XmlHttpRequest,XML,JSON,DOM等 优点:(这也解释了为何我 ...
- 结合prototype和xmlhttprequest封装ajax请求
由于拖延症的严重以及年前准备年会(借口*^__^*) 导致这个小的的思考 现在才算完成 再怎么说也算是上班以来带我的前辈第一次这么正式的给我出题 不管是出于尊重还是自我要求我都决定把它简要的记下来 ...
- Ajax-03 XmlHttpRequest实现Ajax
概述 Ajax主要就是使用XmlHttpRequest对象来完成请求的操作,该对象在主流浏览器中均存在 XmlHttpRequest对象的主要方法 a. void open(String method ...
- XMLHttpRequest实现Ajax异步请求
一.XMLHttpRequest的方法 方法 描述 abort() ...
- C# XMLHttpRequest对象—Ajax实例
Get: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> ...
- 《JavaScript权威指南》学习笔记之二十---XMLHttpRequest和AJAX解决方式
一.AJAX概述 AJAX是Asynchronous JavaScript and XML的缩写.中文译作异步JavaScript和XML.AJAX 不是新的编程语言,而是一种使用现有标准的新方法.在 ...
- 用纯XMLHttpRequest实现AJAX
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...
- 使用 XMLHttpRequest实现Ajax
[XMLHttpRequest的概述] 1.XMLHttpRequest最早是在IE5中以ActiveX组件的形式实现的.非W3C标准 2.创建XMLHttpRequest对象(由于非标准所以实现方法 ...
- Ajax 学习之创建XMLHttpRequest对象------Ajax的核心
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...
随机推荐
- aop计算方法耗时
package necs.omms.common.aop; import lombok.extern.apachecommons.CommonsLog;import org.apache.common ...
- PHP数据结构之一:PHP数据结构基本概念—数据结构
学习任何一种技术都应该先清楚它的基本概念,这是学习任何知识的起点!本文是讲述数据结构的基本概念,适合对数据结构已经有一定基础的程序员,更是适合想要学习数据结构的code一族!让我们开始PHP数据结构的 ...
- Tornado抽象方法抽象类
#!/usr/bin/env python #抽象方法抽象类 import abc class Foo(metaclass=abc.ABCMeta): def f1(self): raise Exce ...
- Java 基于spring 暴露接口 供外部调用
在springmvc的配置文件添加创建如下的bean: <!-- 暴露一个webService连接 --> <bean class="org.springframework ...
- lucene 第二天
Lucene/Solr 第二天 1. 课程计划 Lucene的Field Lucene的索引库维护 lucene的查询 a) Query子对象 b) QueryParser Lucene相关度排序 ...
- 通过kfed自动获取磁盘信息的小脚本
通过kfed自动获取磁盘信息的小脚本 编译KFED [oracle@rac lib]$cd $ORACLE_HOME/rdbms/lib [oracle@rac lib]$ pwd /u01/app/ ...
- 关于mysql自增字段问题
最近遇到mysql字段的自增问题,需要临时处理一下,然后就顺便补补课,这样就有了这样一篇文章. 1.自增值是什么 他是一个字段属性,是用来创建唯一标识的列的 The AUTO_INCREMENT at ...
- EXE DLL等可执行程序添加版本号版权等信息
在使用Microsoft Visual Studio开发工具等编写的exe或者dll等可执行文件时,我们往往需要对这些可执行文件添加版本号,公司,版权等信息. 1. 在我们需要添加各种信息的项目工程中 ...
- 数字图像处理实验(11):PROJECT 05-02,Noise Reduction Using a Median Filter 标签: 图像处理MATLAB 2017-05-26 23:
实验要求: Objective: To understand the non-linearity of median filtering and its noise suppressing abili ...
- Socket编程(c语言示例)
转自:http://blog.csdn.net/dxpqxb/article/details/8166423 前言 Socket可以看成在两个程序进行通讯连接中的一个端点,是连接应用程序和网络驱动程序 ...