一、什么是 Ajax?
Ajax (Asynchronous JavaScript and XML) 是一种无需重新加载整个网页的情况下,能够更新部分网页的技术。通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。
主要特性:
-
异步性 (Asynchronous): 可以在不阻塞用户界面的情况下与服务器进行通信。
-
局部更新 (Partial Updates): 只更新网页的一部分,而不是整个页面,提高了用户体验。
-
基于标准: Ajax 不是一种新技术,而是几种现有技术的组合,包括JavaScript, XML, HTML, CSS。
二、Ajax 的核心对象:XMLHttpRequest
XMLHttpRequest
(XHR) 对象是 Ajax 的核心。它允许浏览器在后台与服务器进行通信。
三、基本语法和步骤 (XMLHttpRequest)
1.创建 XMLHttpRequest 对象:
let xhr;if (window.XMLHttpRequest) { // 现代浏览器xhr = new XMLHttpRequest();
} else { // IE6, IE5xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
2.配置请求 (open 方法):
xhr.open(method, url, async, username, password);
-
method
: HTTP 请求方法 (GET, POST, PUT, DELETE 等)。通常使用 GET 或 POST。 -
url
: 服务器端脚本的 URL。 -
async
: (可选) 布尔值,指示请求是否异步执行。 默认为true
(异步)。 -
username
: (可选) 用于身份验证的用户名。 -
password
: (可选) 用于身份验证的密码。
xhr.open('GET', 'data.txt', true); // 异步 GET 请求
xhr.open('POST', 'submit.php', true); // 异步 POST 请求
3.设置请求头 (可选):
xhr.setRequestHeader(header, value);
-
header
: 请求头的名称。 -
value
: 请求头的值。
重要: 对于 POST
请求,通常需要设置 Content-Type
请求头。
示例:
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // 常用于 POST
xhr.setRequestHeader('Content-Type', 'application/json'); // POST 发送 JSON 数据
4.发送请求 (send 方法):
xhr.send(body); // body 是要发送的数据
body
: (可选) 要发送到服务器的数据。
-
对于
GET
请求,通常body
为null
。 数据应该附加到 URL 上(例如:url?param1=value1¶m2=value2
)。 -
对于
POST
请求,body
可以是:-
null
(如果没有数据要发送) -
URL 编码的字符串 (例如:
param1=value1¶m2=value2
) -
JSON 字符串 (需要设置
Content-Type
为application/json
) -
FormData
对象
-
xhr.send(); // GET 请求,没有数据
xhr.send('name=John&age=30'); // POST 请求,URL 编码的数据
xhr.send(JSON.stringify({name: "John", age: 30})); // POST 请求,JSON 数据
5.处理服务器响应:
使用 onreadystatechange
事件监听 xhr.readyState
的变化。
xhr.onreadystatechange = function() {if (xhr.readyState === 4) { // 请求完成if (xhr.status === 200) { // 请求成功// 处理响应数据let responseText = xhr.responseText; // 字符串形式的响应数据let responseXML = xhr.responseXML; // 如果服务器返回 XML,可以作为 XML 文档访问// 根据你的需求更新页面等console.log("Response: " + responseText);} else {// 处理错误console.error("请求失败,状态码:" + xhr.status);}}
};
-
xhr.readyState
: 表示请求的状态。-
0: 请求未初始化
-
1: 服务器连接已建立
-
2: 请求已接收
-
3: 请求处理中
-
4: 请求已完成,且响应已就绪
-
-
xhr.status
: HTTP 状态码。-
200: "OK" (成功)
-
404: "Not Found" (未找到)
-
500: "Internal Server Error" (服务器内部错误) 等等。
-
四、示例
1.完整的 GET 请求例子
<!DOCTYPE html>
<html>
<head>
<title>简单的 Ajax GET 请求</title>
</head>
<body><button onclick="loadData()">加载数据</button>
<div id="result"></div><script>
function loadData() {let xhr;if (window.XMLHttpRequest) {xhr = new XMLHttpRequest();} else {xhr = new ActiveXObject("Microsoft.XMLHTTP");}xhr.onreadystatechange = function() {if (xhr.readyState === 4) {if (xhr.status === 200) {document.getElementById("result").innerHTML = xhr.responseText;} else {document.getElementById("result").innerHTML = "Error: " + xhr.status;}}};xhr.open("GET", "data.txt", true);xhr.send();
}
</script></body>
</html>
创建一个名为data.txt
的文件,内容例如:Hello, Ajax! This is data loaded from the server.
2.完整的 POST 请求例子
<!DOCTYPE html>
<html>
<head>
<title>简单的 Ajax GET 请求</title>
</head>
<body><button onclick="loadData()">加载数据</button>
<div id="result"></div><script>
function loadData() {let xhr;if (window.XMLHttpRequest) {xhr = new XMLHttpRequest();} else {xhr = new ActiveXObject("Microsoft.XMLHTTP");}xhr.onreadystatechange = function() {if (xhr.readyState === 4) {if (xhr.status === 200) {document.getElementById("result").innerHTML = xhr.responseText;} else {document.getElementById("result").innerHTML = "Error: " + xhr.status;}}};xhr.open("GET", "data.txt", true);xhr.send();
}
</script></body>
</html>
创建一个名为submit.php
的PHP文件(或者其他服务器端语言的文件),例如:
<?php$name = $_POST["name"];echo "你好, " . htmlspecialchars($name) . "!"; // 使用 htmlspecialchars 防止 XSS 攻击
?>
五、使用 FormData 上传文件
FormData
对象提供了一种表示表单数据的键/值对的简单方式,也可以用于上传文件。
<!DOCTYPE html>
<html>
<head>
<title>Ajax 上传文件</title>
</head>
<body><input type="file" id="fileInput"><br><br>
<button onclick="uploadFile()">上传文件</button>
<div id="result"></div><script>
function uploadFile() {let xhr;if (window.XMLHttpRequest) {xhr = new XMLHttpRequest();} else {xhr = new ActiveXObject("Microsoft.XMLHTTP");}xhr.onreadystatechange = function() {if (xhr.readyState === 4) {if (xhr.status === 200) {document.getElementById("result").innerHTML = xhr.responseText;} else {document.getElementById("result").innerHTML = "Error: " + xhr.status;}}};const fileInput = document.getElementById("fileInput");const file = fileInput.files[0];const formData = new FormData();formData.append("file", file); // 添加文件到 FormDataxhr.open("POST", "upload.php", true);xhr.send(formData); // 不需要手动设置 Content-Type,浏览器会自动设置
}
</script></body>
</html>
创建一个名为upload.php
的PHP文件(或者其他服务器端语言的文件),例如:
<?php
if (isset($_FILES["file"])) {$file = $_FILES["file"];// 安全起见,你应该进行各种检查,例如文件类型、大小等// 示例:$allowed_types = array("image/jpeg", "image/png", "application/pdf");if (!in_array($file["type"], $allowed_types)) {echo "Error: Invalid file type.";exit;}$upload_dir = "uploads/"; // 确保该目录存在,并且有写入权限$filename = basename($file["name"]); // 获取文件名$target_path = $upload_dir . $filename;if (move_uploaded_file($file["tmp_name"], $target_path)) {echo "文件上传成功!文件名: " . htmlspecialchars($filename);} else {echo "文件上传失败。";}} else {echo "没有文件上传。";
}
?>