AJAX GET 请求
GET 请求
GET 请求用于从服务器检索数据。在此请求中,数据将作为附加在请求末尾的 URL 的一部分发送。我们可以将此请求与 open() 方法一起使用。
语法:
open(GET, url, true)
其中,open() 方法需要三个参数 -
GET - 它用于从服务器检索数据。
url - url表示将在Web服务器上打开的文件。
true − 对于异步连接,将值设置为 true。或者,对于同步连接,将值设置为 false。此参数的默认值为 true。
使用示例:
<!DOCTYPE html>
<html>
<head>
<script>
function ShowData() {
// 创建 XMLHttpRequest 对像
var xhrRequest = new XMLHttpRequest();
// 定义回调函数
xhrRequest.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("example").innerHTML = this.responseText;
}
};
// 打开连接
xhrRequest.open("GET", "/tutorial/static/prov.txt", true);
// 向服务器发送请求
xhrRequest.send();
}
</script>
</head>
<body>
<div id="example">
<p>请点击下面的按钮查询数据:</p>
<button type="button" onclick="ShowData()">查询</button>
</div>
</body>在上面的示例中,我们使用 XMLHttpRequest 中的 GET 请求 “/tutorial/static/prov.txt”API 从服务器prov.txt 文件数据。因此,单击按钮后,我们将从服务器获取prop.txt中的数据。