AJAX异步通信主要用fetch和XMLHttpRequest,fetch基于Promise语法简洁,支持async/await,成为主流选择;XMLHttpRequest兼容性好但代码冗长。1. fetch发送GET请求:fetch('url').then(res => res.json()).then(data => console.log(data));2. 使用async/await更清晰:async function getData(){ const res = await fetch('url'); if(!res.ok) throw new Error(); const data = await res.json(); };3. POST请求需设置method、headers和stringify的body;4. XMLHttpRequest需监听onreadystatechange,readyState为4且status为200时表示成功,需手动解析JSON;5. fetch默认不报错需检查response.ok,可用AbortController取消请求;6. 推荐优先使用fetch,复杂场景可选axios等库。

AJAX(Asynchronous JavaScript and XML)是前端开发中实现异步通信的核心技术,它允许我们在不刷新页面的情况下与服务器交换数据。在现代JavaScript中,发送AJAX请求主要有两种方式:传统的 XMLHttpRequest(常通过jQuery封装使用),以及更现代的 fetch API。下面详细介绍这两种方法的实际用法。
fetch 是浏览器原生提供的API,基于 Promise,语法简洁,支持 async/await,已成为主流选择。
● 基本 GET 请求:获取数据是最常见的操作。
示例:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('网络错误');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('请求失败:', error);
});
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) throw new Error('请求失败');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('错误:', error);
}
}
getData();
async function postData() {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: '张三',
age: 25
})
});
if (!response.ok) throw new Error('提交失败');
const result = await response.json();
console.log(result);
}
postData();
虽然 fetch 更现代,但了解 XMLHttpRequest 有助于理解底层机制。
● 简单 GET 请求示例:const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.send();
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/users', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 201) {
console.log('创建成功');
}
};
xhr.send(JSON.stringify({ name: '李四', age: 30 }));
两者都能实现异步请求,但存在明显差异:
const controller = new AbortController();
fetch('/api/data', { signal: controller.signal })
.then(res => res.json())
.then(data => console.log(data));
// 在需要时取消请求
controller.abort();
以上就是JS AJAX请求怎么发送_JS AJAX异步请求与fetchAPI使用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号