一、什么是 AJAX?
AJAX(Asynchronous JavaScript and XML)是一种用于创建异步 Web 应用的技术,它允许网页在不重新加载整个页面的情况下,与服务器交换数据。这使得 Web 应用更具交互性和响应性。
二、URL 在 AJAX 中的作用
URL(统一资源定位符)是 AJAX 请求的重要组成部分。它用于指定请求数据的地址。URL 可以是:
- 相对 URL(如
/api/data):指向当前网站的资源。 - 绝对 URL(如
https://example.com/api/data):指向外部服务器的资源。
URL 还可以包含查询参数,以传递数据给服务器,例如:
https://example.com/api/data?name=Tom&age=25
三、使用 AJAX 发送请求
1. 使用 XMLHttpRequest 发送 GET 请求
文件名:ajax_get.html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX GET 请求示例</title>
</head>
<body>
<h2>点击按钮发送 AJAX GET 请求</h2>
<button onclick="sendRequest()">发送请求</button>
<p id="result"></p>
<script>
function sendRequest() {
var xhr = new XMLHttpRequest();
var url = "https://jsonplaceholder.typicode.com/posts/1"; // 这是一个测试 API
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
xhr.send();
}
</script>
</body>
</html>
运行结果:
点击按钮后,页面会显示从 https://jsonplaceholder.typicode.com/posts/1 获取的数据,例如:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit suscipit..."
}
2. 使用 fetch 发送 POST 请求
文件名:ajax_post.html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX POST 请求示例</title>
</head>
<body>
<h2>点击按钮发送 AJAX POST 请求</h2>
<button onclick="sendPostRequest()">发送请求</button>
<p id="response"></p>
<script>
function sendPostRequest() {
var url = "https://jsonplaceholder.typicode.com/posts"; // 测试 API
var data = {
title: "Hello AJAX",
body: "AJAX 发送的测试数据",
userId: 1
};
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
document.getElementById("response").innerHTML = JSON.stringify(data, null, 2);
})
.catch(error => console.error("Error:", error));
}
</script>
</body>
</html>
运行结果:
点击按钮后,页面会显示服务器返回的 JSON 数据,例如:
{
"title": "Hello AJAX",
"body": "AJAX 发送的测试数据",
"userId": 1,
"id": 101
}
四、总结
- AJAX 让网页与服务器交互时无需刷新整个页面,提高用户体验。
- URL 用于指定 AJAX 请求的目标地址,可以是相对路径或绝对路径。
XMLHttpRequest和fetch是两种常见的 AJAX 发送方式,其中fetch更现代,使用更简单。
希望这篇博客能帮助大家更深入理解 AJAX 和 URL 的关系,并能够实际应用到自己的项目中!