对于等待响应的情况,可以使用JavaScript的“阻塞I/O”机制,即通过XMLHttpRequest对象向服务器发送请求,并以同步方式等待响应。以下是一个示例:
function handleClick() {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/resource', false); // 第三个参数设置为false表示使用同步方式
xhr.send();
// 等待响应
if (xhr.readyState === 4 && xhr.status === 200) {
// 处理响应
console.log(xhr.responseText);
}
}
对于异步获取响应的情况,可以使用XMLHttpRequest对象的异步方式,或使用fetch API。以下是一个使用XMLHttpRequest对象的示例:
function handleClick() {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/resource', true); // 第三个参数设置为true表示使用异步方式
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// 处理响应
console.log(xhr.responseText);
}
}
xhr.send();
}
使用fetch API的示例:
function handleClick() {
fetch('/path/to/resource')
.then(function(response) {
return response.text();
})
.then(function(text) {
// 处理响应
console.log(text);
});
}