使用原生 JavaScript 发送 AJAX(Asynchronous JavaScript and XML)请求是一种常见的与服务器进行异步通信的方法。尽管现代开发中更常用 fetch
API 或第三方库(如 Axios),但了解 AJAX 的基础概念仍然非常重要。
AJAX 允许网页在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页内容。它主要依赖于 XMLHttpRequest
对象来实现。
AJAX 请求主要分为以下几种类型:
以下是使用原生 JavaScript 发送 AJAX GET 和 POST 请求的示例:
// 创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
// 配置请求
xhr.open('GET', 'https://api.example.com/data', true);
// 设置响应类型
xhr.responseType = 'json';
// 注册回调函数
xhr.onload = function() {
if (xhr.status === 200) {
console.log('成功:', xhr.response);
} else {
console.error('错误:', xhr.statusText);
}
};
// 处理网络错误
xhr.onerror = function() {
console.error('网络错误');
};
// 发送请求
xhr.send();
// 创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
// 配置请求
xhr.open('POST', 'https://api.example.com/data', true);
// 设置请求头
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
// 注册回调函数
xhr.onload = function() {
if (xhr.status === 201) { // 201 Created
console.log('成功:', xhr.response);
} else {
console.error('错误:', xhr.statusText);
}
};
// 处理网络错误
xhr.onerror = function() {
console.error('网络错误');
};
// 发送请求体
var data = JSON.stringify({
name: 'John',
age: 30
});
xhr.send(data);
xhr.timeout
并处理 timeout
事件。xhr.timeout
并处理 timeout
事件。通过以上示例和说明,希望能帮助你更好地理解和使用原生 JavaScript 发送 AJAX 请求。
领取专属 10元无门槛券
手把手带您无忧上云