AJAX – 向服务器发送请求
使用 AJAX(XMLHttpRequest
或 fetch()
)可以向服务器发送请求,而无需刷新整个页面。常见的 HTTP 请求方式包括 GET
和 POST
,但 PUT
、DELETE
也常用于 REST API。
1. 使用 XMLHttpRequest 发送 GET 请求
示例:从服务器获取数据
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("服务器返回的数据:", xhr.responseText);
}
};
xhr.send(); // GET 请求不需要请求体
解析
xhr.open("GET", "data.txt", true)
:指定GET
请求和目标 URL,true
代表异步。xhr.send()
:发送请求,无需请求体。xhr.onreadystatechange
:监听请求状态,当readyState === 4 && status === 200
时表示成功。
2. 使用 XMLHttpRequest 发送 POST 请求
示例:向服务器发送数据
var xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("服务器返回:", xhr.responseText);
}
};
xhr.send("name=张三&age=25");
解析
xhr.open("POST", "submit.php", true)
:指定POST
请求。xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
:告诉服务器传输的内容类型。xhr.send("name=张三&age=25")
:发送表单格式数据。
3. 发送 JSON 数据(推荐)
示例:POST 请求发送 JSON
var xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = JSON.stringify({ name: "张三", age: 25 });
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("服务器返回:", xhr.responseText);
}
};
xhr.send(data);
解析
- 发送的数据格式为
JSON
,需要JSON.stringify(data)
转换对象。 Content-Type
设置为"application/json"
以告知服务器。
4. 使用 Fetch API 发送请求(推荐)
现代浏览器推荐使用 fetch()
,语法更简洁。
GET 请求
fetch("data.txt")
.then(response => response.text())
.then(data => console.log("服务器返回:", data))
.catch(error => console.error("请求失败:", error));
POST 请求
fetch("submit.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name: "张三", age: 25 })
})
.then(response => response.json())
.then(data => console.log("服务器返回:", data))
.catch(error => console.error("请求失败:", error));
解析
fetch()
返回Promise
,可以链式.then()
处理数据。headers
设置Content-Type
以发送 JSON 数据。
5. 处理错误
超时和错误处理
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true);
xhr.timeout = 5000; // 5秒超时
xhr.ontimeout = function() {
console.error("请求超时!");
};
xhr.onerror = function() {
console.error("请求出错!");
};
xhr.send();
Fetch API 处理错误
fetch("data.txt")
.then(response => {
if (!response.ok) {
throw new Error("HTTP 错误, 状态码: " + response.status);
}
return response.text();
})
.then(data => console.log(data))
.catch(error => console.error("请求失败:", error));
6. 发送其他 HTTP 请求
PUT 请求
fetch("update.php", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: 1, name: "李四" })
})
.then(response => response.json())
.then(data => console.log("更新成功:", data))
.catch(error => console.error("更新失败:", error));
DELETE 请求
fetch("delete.php?id=1", { method: "DELETE" })
.then(response => response.json())
.then(data => console.log("删除成功:", data))
.catch(error => console.error("删除失败:", error));
总结
XMLHttpRequest
适用于所有浏览器,但fetch()
更现代、语法简洁。GET
请求用于获取数据,POST
请求用于提交数据,PUT
更新数据,DELETE
删除数据。- 推荐使用
fetch()
处理 AJAX 请求,并结合async/await
进行优化。
🔹 推荐:fetch()
+ JSON 进行 AJAX 交互,代码更简洁高效! 🚀
发表回复