js实现 ajaxsubmit
使用原生JavaScript实现Ajax表单提交
创建XMLHttpRequest对象并配置请求
通过new XMLHttpRequest()实例化对象,使用open()方法设置请求方法(GET/POST)和URL,setRequestHeader()可设置Content-Type为表单编码格式。
const xhr = new XMLHttpRequest();
xhr.open('POST', 'submit.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
处理表单数据序列化
通过FormData对象自动收集表单元素的值,或手动拼接键值对字符串。使用encodeURIComponent()确保特殊字符正确编码。
const form = document.getElementById('myForm');
const formData = new FormData(form);
// 或手动序列化
let data = '';
for(let [key, value] of formData) {
data += `${encodeURIComponent(key)}=${encodeURIComponent(value)}&`;
}
发送请求并处理响应
通过send()方法提交数据,监听onreadystatechange事件。当readyState为4且status为200时处理响应数据。
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
// 处理服务器返回的数据
}
};
xhr.send(data);
使用Fetch API实现更简洁的提交
现代浏览器支持更简洁的Fetch API方案,使用Promise链式调用处理异步操作。注意需设置正确的请求头并处理响应数据。
fetch('submit.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(new FormData(form))
})
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
错误处理与状态反馈
添加网络错误和超时处理逻辑,通过DOM操作更新页面状态提示用户。设置合理的超时时间并使用abort()方法终止长时间未响应的请求。
xhr.timeout = 5000;
xhr.ontimeout = () => alert('请求超时');
xhr.onerror = () => alert('网络错误');
实际应用中的注意事项
跨域请求需服务端配置CORS头部,提交前应进行表单验证。对于文件上传需设置multipart/form-data类型。考虑添加CSRF令牌防止跨站请求伪造攻击。

// 添加CSRF令牌示例
data += `&csrf_token=${encodeURIComponent(token)}`;






