diff --git "a/\350\224\241\347\216\256\351\223\255/20241202 XHR\344\270\216AXIOS/20241202 XHR\344\270\216AXIOS.md" "b/\350\224\241\347\216\256\351\223\255/20241202 XHR\344\270\216AXIOS/20241202 XHR\344\270\216AXIOS.md" new file mode 100644 index 0000000000000000000000000000000000000000..6178d87d2cec4963bb33c1eab00392a971bad551 --- /dev/null +++ "b/\350\224\241\347\216\256\351\223\255/20241202 XHR\344\270\216AXIOS/20241202 XHR\344\270\216AXIOS.md" @@ -0,0 +1,453 @@ +## 课堂笔记 + +#### **XHR** + +```javascript +// 创建一个 XMLHttpRequest 对象 +const xhr = new XMLHttpRequest(); + +// 使用 +// GET +xhr.open('GET', 'https://api.example.com/data', true); +xhr.onreadystatechange = function() { + if (xhr.readyState === 4 && xhr.status === 200) { + console.log(xhr.responseText); // 处理响应 + } +}; +xhr.send(null); + +// POST +xhr.open('POST', 'https://api.example.com/submit', true); +xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); +xhr.onreadystatechange = function() { + if (xhr.readyState === 4 && xhr.status === 200) { + console.log(xhr.responseText); + } +}; +// 假设我们发送的是 JSON 格式的数据 +const data = JSON.stringify({key1: 'value1', key2: 'value2'}); +xhr.send(data); +``` + +#### **AXIOS** + +```javascript +// 导入 + + +// 使用 +// GET +axios.get('https://api.example.com/data') + .then(function (response) { + // 成功处理 + console.log(response.data); + }) + .catch(function (error) { + // 错误处理 + console.error(error); + }); + +// POST +// 发送 JSON 数据 +axios.post('https://api.example.com/submit', { + key1: 'value1', + key2: 'value2' + }) + .then(function (response) { + console.log(response.data); + }) + .catch(function (error) { + console.error(error); + }); +``` + +## 课后作业 + +#### **异步请求响应页面** + +**index.html** + +```html + + + +
+ + +