1、AJAX - XMLHttpRequest 对象
1.1 XMLHttpRequest
对象是 AJAX
的基石。
- 创建
XMLHttpRequest
对象 - 定义回调函数
- 打开
XMLHttpRequest
对象 - 向服务器发送请求
1.2 XMLHttpRequest 对象
所有现代浏览器都支持 XMLHttpRequest
对象。
XMLHttpRequest
对象可用于在后台与 Web
服务器交换数据。这意味着可以更新网页的部分内容,而无需重新加载整个页面。
1.3 创建 XMLHttpRequest 对象
所有现代浏览器(Chrome、Firefox、IE、Edge、Safari、Opera)都有内置的 XMLHttpRequest
对象。
创建 XMLHttpRequest
对象的语法:
html
variable = new XMLHttpRequest();
1.4 定义回调函数
回调函数是作为参数传递给另一个函数的函数。
在这种情况下,回调函数应包含响应准备就绪时要执行的代码。
html
xhttp.onload = function() {
// 当响应准备就绪时要做什么
}
1.5 发送请求
如需向服务器发送请求,您可以使用 XMLHttpRequest 对象的 open() 和 send() 方法:
html
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
示例:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button onclick="myFunction()">更改内容</button>
<p id="demo">内容</p>
<!-- 请确保替换path/to/your/file.txt为你的txt文件的实际路径。
如果你在客户端浏览器中尝试这个代码,它将不会工作,因为出于安全原因,
现代浏览器不允许通过XMLHttpRequest或fetch直接访问本地文件系统。
如果你需要在客户端操作文件,你可能需要使用HTML的<input type="file">元素允许用户
选择文件,然后使用FileReader API来读取文件内容。 -->
<script>
function myFunction() {
const xhttp = new XMLHttpRequest();
xhttp.open("GET", "/text/demo.txt");
xhttp.responseText = "text";
xhttp.onload = function () {
document.getElementById("demo").innerHTML = xhttp.responseText;
};
xhttp.send();
}
</script>
</body>
</html>
1.6 跨域访问(Access Across Domains)
出于安全原因,现代浏览器不允许跨域访问。
这意味着网页和它尝试加载的 XML 文件必须位于同一台服务器上。
W3School 上的例子都打开位于 W3School 域中的 XML 文件。
如果您想在自己的网页之一上使用上面的例子,您加载的 XML 文件必须位于您自己的服务器上。
1.7 XMLHttpRequest 对象方法

1.8 XMLHttpRequest 对象属性

1.8.1 onload 属性
使用 XMLHttpRequest
对象时,您可以定义一个回调函数,以便在请求收到答复时执行。
请在 XMLHttpRequest
对象的 onload
属性中定义该函数:
实例见1.5
1.8.2 多个回调函数
如果网站中有多个 AJAX
任务,则应创建一个执行 XMLHttpRequest
对象的函数,并为每个 AJAX
任务创建一个回调函数。
函数调用应包含 URL
以及响应准备就绪时要调用的函数。
实例:
html
loadDoc("url-1", myFunction1);
loadDoc("url-2", myFunction2);
function loadDoc(url, cFunction) {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {cFunction(this);}
xhttp.open("GET", url);
xhttp.send();
}
function myFunction1(xhttp) {
// 这里是动作
}
function myFunction2(xhttp) {
// 这里是动作
}
1.8.3 onreadystatechange 属性
readyState
属性保存 XMLHttpRequest
的状态。
onreadystatechange
属性定义了一个回调函数,当 readyState
改变时执行该函数。
status
属性和 statusText
属性保存 XMLHttpRequest
对象的状态。

每次 readyState 改变时都会调用 onreadystatechange 函数。
当 readyState 为 4 且 status 为 200 时,响应就绪:
html
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h1>XMLHttpRequest 对象</h1>
<button type="button" onclick="loadDoc()">更改内容</button>
</div>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "/demo/js/ajax_info.txt");
xhttp.send();
}
</script>
</body>
</html>
onreadystatechange 事件被触发了四次(1-4),每次 readyState 变化一次。
2、AJAX - XMLHttpRequest
XMLHttpRequest
对象用于同服务器交换数据。
2.1 向服务器发送请求
如需向服务器发送请求,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:
html
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

2.2 GET 还是 POST?
GET
比 POST
更简单更快,可用于大多数情况下。
不过,请在以下情况始终使用 POST
:
- 缓存文件不是选项(更新服务器上的文件或数据库)
- 向服务器发送大量数据(
POST
无大小限制) - 发送用户输入(可包含未知字符),
POST
比GET
更强大更安全
2.3 GET 请求
一条简单的 GET 请求:
html
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();
在上面的例子中,您可能会获得一个缓存的结果。为了避免此情况,请向 URL 添加一个唯一的 ID:
html
xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);
xhttp.send();
如果您需要用 GET 方法来发送信息,请向 URL 添加这些信息:
html
xhttp.open("GET", "demo_get2.asp?fname=Bill&lname=Gates", true);
xhttp.send();
2.4 POST 请求
一条简单的 POST 请求:
html
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();
如需像 HTML 表单那样 POST 数据,请通过 setRequestHeader() 添加一个 HTTP 头部。请在 send() 方法中规定您需要发送的数据:
html
xhttp.open("POST", "ajax_test.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Bill&lname=Gates");

2.5 url - 服务器上的文件
open()
方法的 url
参数,是服务器上文件的地址:
html
xhttp.open("GET", "ajax_test.asp", true);
该文件可以是任何类型的文件,如 .txt
和 .xml
,或服务器脚本文件,如 .asp
和 .php
(它们可以在发送回响应之前在服务器执行操作)。
2.6 异步 - true 还是 false?
如需异步发送请求,open() 方法的 async 参数必须设置为 true:
html
xhttp.open("GET", "ajax_test.asp", true);
发送异步请求对 web 开发人员来说是一个巨大的进步。服务器上执行的许多任务都非常耗时。在 AJAX 之前,此操作可能会导致应用程序挂起或停止。
通过异步发送,JavaScript 不必等待服务器响应,而是可以:
- 在等待服务器响应时执行其他脚本
- 当响应就绪时处理响应
2.7 onreadystatechange 属性
通过 XMLHttpRequest
对象,您可以定义当请求接收到应答时所执行的函数。
这个函数是在 XMLHttpResponse
对象的 onreadystatechange
属性中定义的:
html
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h1>XMLHttpRequest 对象</h1>
<button type="button" onclick="loadDoc()">更改内容</button>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "/demo/js/ajax_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
2.8 同步请求
如需执行同步的请求,请把 open()
方法中的第三个参数设置为 false
:
html
xhttp.open("GET", "ajax_info.txt", false);
有时 async = false
用于快速测试。你也会在更老的 JavaScript 代码中看到同步请求。
由于代码将等待服务器完成,所以不需要 onreadystatechange
函数:
html
<!DOCTYPE html>
<html>
<body>
<h1>XMLHttpRequest 对象</h1>
<p id="demo">让 AJAX 更改这段文本。</p>
<button type="button" onclick="loadDoc()">更改内容</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "/demo/js/ajax_info.txt", false);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;
}
</script>
</body>
</html>
我们不推荐同步的 XMLHttpRequest (async = false)
,因为 JavaScript 将停止执行直到服务器响应就绪。如果服务器繁忙或缓慢,应用程序将挂起或停止。
同步 XMLHttpRequest
正在从 Web 标准中移除,但是这个过程可能需要很多年。
现代开发工具被鼓励对使用同步请求做出警告,并且当这种情况发生时,可能会抛出 InvalidAccessError
异常。
3、AJAX - 服务器响应
3.1 onreadystatechange 属性
readyState
属性存留 XMLHttpRequest
的状态。
onreadystatechange
属性定义当 readyState
发生变化时执行的函数。
status
属性和 statusText
属性存有 XMLHttpRequest
对象的状态。

每当 readyState 发生变化时就会调用 onreadystatechange 函数。
更多信息:
AJAX - 服务器响应
AJAX XML 实例
AJAX PHP 实例
AJAX ASP 实例
AJAX Database 实例
XML 应用程序
AJAX 实例