手写一个简易的ajax请求
# 问题: 手写一个简易的ajax请求
<!DOCTYPE html>
<html>
<head>
<title>AJAX 示例</title>
<script>
function makeAjaxRequest() {
var xhr = new XMLHttpRequest(); // 创建一个新的XMLHttpRequest对象
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) { // 检查响应状态
document.getElementById('response').innerHTML = xhr.responseText; // 更新页面上的内容
} else {
alert('发生错误: ' + xhr.status); // 处理错误
}
}
};
xhr.open('GET', 'https://example.com/api/data', true); // 准备请求
xhr.send(); // 发送请求
}
</script>
</head>
<body>
<h1>点击按钮加载数据</h1>
<button onclick="makeAjaxRequest()">加载数据</button>
<div id="response"></div>
</body>
</html>
我们定义了一个 makeAjaxRequest
函数来发起 AJAX 请求。当用户点击按钮时,这个函数会创建一个 XMLHttpRequest 对象并发送一个 GET 请求到指定的 URL。在请求完成时,通过检查 readyState
和 status
来处理响应,并更新页面上的内容或处理错误。
请注意,这只是一个简单的示例,实际的 AJAX 请求可能会涉及更多的配置和处理