AJAX总结
AJAX 知识总结
一、AJAX 基础概念
1. 什么是 AJAX
AJAX (Asynchronous JavaScript And XML) 是一种在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术。它允许:
- 异步无刷新请求
- 无需更新整个页面就能加载数据
- 增强用户体验和交互性
2. AJAX 工作原理
- 浏览器创建 XMLHttpRequest 对象
- 通过该对象向服务器发送请求
- 服务器处理请求并返回响应
- 浏览器接收响应并更新页面内容
3. AJAX 优缺点
优点:
- 无需刷新页面即可与服务器通信
- 允许根据用户事件更新部分页面内容
- 减少服务器负载和带宽消耗
- 提高用户体验
缺点:
- 无浏览历史,不能回退
- 存在跨域问题(同源策略限制)
- 对搜索引擎优化(SEO)不友好
- 可能增加服务器请求次数
二、AJAX 核心技术
1. XMLHttpRequest 对象
AJAX 的核心对象,用于与服务器交互。
基本使用步骤:
// 1. 创建对象
const xhr = new XMLHttpRequest();// 2. 设置请求方法和URL
xhr.open(method, url);// 3. 发送请求
xhr.send(body); // GET请求不传body参数// 4. 事件绑定,处理服务端返回的结果
xhr.onreadystatechange = function() {if(xhr.readyState === 4 && xhr.status === 200) {console.log(xhr.responseText);}
}
2. 请求状态
xhr.readyState
表示请求状态:
- 0: 未初始化,尚未调用open()
- 1: 已调用open(),未调用send()
- 2: 已调用send(),收到响应头
- 3: 正在接收响应体
- 4: 请求完成,响应就绪
3. HTTP 请求与响应
请求报文:
- 请求行:方法、URL、协议版本
- 请求头:Host、Cookie、Content-Type等
- 请求体:参数数据
响应报文:
- 响应状态行:状态码、状态文本
- 响应头:Content-Type、Content-Length等
- 响应体:HTML/JSON/JS/CSS等数据
4. 请求方法
- GET:从服务器读取数据
- POST:向服务器添加新数据
- PUT:更新服务器数据
- DELETE:删除服务器数据
5. 请求体参数格式
application/x-www-form-urlencoded
:键值对参数application/json
:JSON字符串multipart/form-data
:文件上传
三、AJAX 高级特性
1. 超时与网络异常处理
// 设置超时时间(毫秒)
xhr.timeout = 2000;// 超时回调
xhr.ontimeout = function() {alert('请求超时');
};// 网络异常回调
xhr.onerror = function() {alert('网络异常');
};
2. 取消请求
xhr.abort(); // 中断请求
3. 重复请求问题
通过标识变量判断是否正在发送请求,避免重复请求。
4. IE 缓存问题
IE浏览器会缓存AJAX请求结果,解决方法是在URL后添加时间戳参数:
xhr.open("get", "/testAJAX?t=" + Date.now());
四、AJAX 封装工具
1. jQuery 中的 AJAX
// GET请求
$.get(url, [data], [callback], [type]);// POST请求
$.post(url, [data], [callback], [type]);// 通用方法
$.ajax({url: '...',type: 'GET/POST',data: {...},dataType: 'json',success: function(data) {...},error: function() {...},timeout: 2000,headers: {...}
});
2. axios
基于Promise的HTTP客户端,支持浏览器和Node.js。
基本使用:
// GET请求
axios.get(url, {params: {...}, // URL参数headers: {...} // 请求头
}).then(response => {...});// POST请求
axios.post(url, data, {params: {...},headers: {...}
}).then(response => {...});// 通用方法
axios({method: 'post',url: '...',data: {...},headers: {...}
}).then(response => {...});
3. fetch API
现代浏览器原生支持的API,返回Promise对象:
fetch(url, {method: 'POST',headers: {...},body: '...'
}).then(response => {if(response.ok) {return response.json();}throw new Error('Network error');
}).then(data => {...});
五、跨域问题与解决方案
1. 同源策略
浏览器安全策略,要求协议、域名、端口完全相同。
2. JSONP
利用<script>
标签的跨域能力,只支持GET请求。
原理:
- 前端定义回调函数
- 动态创建script标签,src指向跨域API
- 服务器返回函数调用,参数为数据
实现:
function handle(data) {console.log(data);
}const script = document.createElement('script');
script.src = 'http://other.com/api?callback=handle';
document.body.appendChild(script);
jQuery实现:
$.ajax({url: 'http://other.com/api',dataType: 'jsonp',success: function(data) {...}
});
3. CORS (跨域资源共享)
服务器端设置响应头允许跨域:
// 允许所有源
response.setHeader('Access-Control-Allow-Origin', '*');// 允许特定源
response.setHeader('Access-Control-Allow-Origin', 'http://allowed.com');// 允许自定义头
response.setHeader('Access-Control-Allow-Headers', '*');// 允许的方法
response.setHeader('Access-Control-Allow-Methods', '*');
六、Node.js 服务器端实现
1. 基本服务器
const http = require('http');
http.createServer((req, res) => {res.writeHead(200, {'Content-Type': 'text/plain'});res.end('Hello World\n');
}).listen(8888);
2. Express 框架
const express = require('express');
const app = express();// 路由规则
app.get('/', (req, res) => {res.send('Hello Express');
});// 监听端口
app.listen(8000, () => {console.log('Server running...');
});
3. 处理AJAX请求
app.all('/api', (req, res) => {// 设置CORS头res.setHeader('Access-Control-Allow-Origin', '*');res.setHeader('Access-Control-Allow-Headers', '*');// 响应JSON数据const data = {name: 'example'};res.send(JSON.stringify(data));
});
七、实际应用技巧
1. 处理JSON数据
// 自动转换响应数据为JSON
xhr.responseType = 'json';
xhr.onload = function() {console.log(xhr.response); // 已经是JSON对象
};// 手动转换
const data = JSON.parse(xhr.responseText);
2. 进度事件
xhr.onprogress = function(event) {if(event.lengthComputable) {const percent = (event.loaded / event.total) * 100;console.log(percent + '%');}
};
3. 表单数据处理
// FormData对象处理表单
const formData = new FormData(document.getElementById('form'));
xhr.send(formData);
4. 错误处理
xhr.onerror = function() {// 网络错误处理
};xhr.onreadystatechange = function() {if(xhr.readyState === 4) {if(xhr.status === 200) {// 成功处理} else {// HTTP错误状态码处理console.error('Error:', xhr.status, xhr.statusText);}}
};