1. AJAX(Asynchronous JavaScript and XML)
AJAX 是一种在不刷新整个页面的情况下,与服务器进行异步通信并更新部分网页的技术。核心是 XMLHttpRequest 对象(现代也可用 fetch API)。它能实现网页的局部更新,提升用户体验。其工作流程通常为创建请求对象、打开连接、发送请求、监听状态变化处理响应。
代码示例(使用 XMLHttpRequest 实现 GET 请求)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX GET 请求示例</title>
</head>
<body>
<button id="fetchData">获取数据</button>
<div id="result"></div>
<script>
const button = document.getElementById('fetchData');
const resultDiv = document.getElementById('result');
button.addEventListener('click', () => {
const xhr = new XMLHttpRequest();
const url = 'https://jsonplaceholder.typicode.com/todos/1';
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
resultDiv.innerHTML = `<p>ID: ${response.id}, Title: ${response.title}</p>`;
} else {
resultDiv.innerHTML = `<p>请求失败,状态码: ${xhr.status}</p>`;
}
}
};
xhr.send();
});
</script>
</body>
</html>
2. HTTP 协议(Hyper - Text Transfer Protocol)
HTTP 是用于传输超文本的应用层协议,基于请求 - 响应模型。
- 请求方法:
- GET:从服务器获取资源,参数附在 URL 后,如
http://example.com/api?param1=value1。 - POST:向服务器提交数据,数据在请求体中,常用于表单提交。
- PUT:更新服务器上的资源。
- DELETE:删除服务器上的资源。
- GET:从服务器获取资源,参数附在 URL 后,如
- 状态码:
- 2xx:成功,如 200 OK 表示请求成功。
- 3xx:重定向,如 301 Moved Permanently 表示永久重定向。
- 4xx:客户端错误,如 404 Not Found 表示请求的资源不存在。
- 5xx:服务器错误,如 500 Internal Server Error 表示服务器内部错误。
- 请求和响应头:包含各种元信息,如
Content - Type表示数据类型,User - Agent表示客户端信息。
代码示例(使用 Node.js 的 http 模块创建简单服务器处理 GET 请求)
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
res.writeHead(200, { 'Content - Type': 'text/plain' });
res.end('Hello, World!');
} else {
res.writeHead(404, { 'Content - Type': 'text/plain' });
res.end('404 Not Found');
}
});
const port = 3000;
server.listen(port, () => {
console.log(`服务器运行在 http://localhost:${port}`);
});
3. Promise
Promise 是异步编程的解决方案,避免回调地狱。它有三种状态:pending(进行中)、fulfilled(已成功)、rejected(已失败)。通过 then() 处理成功结果,catch() 处理失败原因,还可链式调用。
代码示例
function asyncOperation() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
resolve('操作成功');
} else {
reject('操作失败');
}
}, 1000);
});
}
asyncOperation()
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error(error);
});
4. Axios
Axios 是基于 Promise 的 HTTP 客户端,可用于浏览器和 Node.js。它支持拦截请求和响应、自动转换 JSON 数据等功能。
代码示例(浏览器环境)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Axios 请求示例</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<button id="fetchWithAxios">使用 Axios 获取数据</button>
<div id="axiosResult"></div>
<script>
const axiosButton = document.getElementById('fetchWithAxios');
const axiosResultDiv = document.getElementById('axiosResult');
axiosButton.addEventListener('click', () => {
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => {
const data = response.data;
axiosResultDiv.innerHTML = `<p>ID: ${data.id}, Title: ${data.title}</p>`;
})
.catch((error) => {
axiosResultDiv.innerHTML = `<p>请求失败: ${error.message}</p>`;
});
});
</script>
</body>
</html>
代码示例(Node.js 环境)
const axios = require('axios');
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
2856

被折叠的 条评论
为什么被折叠?



