两个ajax同时请求后台数据库资源的解决办法
warning:
这篇文章距离上次修改已过200天,其中的内容可能已经有所变动。
要同时发送两个AJAX请求并处理它们的结果,可以使用JavaScript的Promise对象和fetch
函数(或jQuery的$.ajax
)。以下是使用原生JavaScript的示例代码:
// 使用fetch发送请求并返回Promise
function sendRequest(url) {
return fetch(url)
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Network response was not ok.');
})
.catch(error => {
console.error('Fetch error:', error);
});
}
// 发送两个并行的请求
const request1 = sendRequest('https://your-backend-endpoint1.com');
const request2 = sendRequest('https://your-backend-endpoint2.com');
// 使用Promise.all等待两个请求都完成
Promise.all([request1, request2])
.then(responses => {
// 这里的responses是两个请求返回的结果数组
console.log('Both requests succeeded:', responses);
})
.catch(error => {
console.error('One or both requests failed:', error);
});
这段代码首先定义了一个sendRequest
函数,该函数接受一个URL并返回一个Promise,该Promise将在请求完成时解决。然后,我们发送两个请求,并使用Promise.all
来确定两个请求都已成功解决。如果任何一个请求失败,错误将被捕获并在控制台中记录。
评论已关闭