基本使用
xhr = new XMLHttpRequest();
xhr.open('get/post', 'url');
xhr.send(); // 如果是post请求则需要xhr.send(string);
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) { // 如果请求完成,并且状态是200
console.log(xhr.response); // 请求的结果
};
};
处理数据
其实不管请求是GET还是POST,处理的方式都是一样的,只不过是使用的位置不一样。
需要将数据转换成如下格式:
‘account=xxx&password=xxx’
这里以表单举例。
html部分
<form id="info" action="" onsubimt="return handleAjax()" >
<input data-name="account" type="text" placeholder="请输入账号" />
<input data-name="password" type="password" placeholder="请输入密码" />
<input type="submit" value="提交" />
</form>
javascript部分
function handleAjax() {
const input_list = document.getElementById('info').children;
const input_obj = {};
for(let i = 0; i < input_list.length - 1; i++) {
obj[input_list[i].dataset.name] = input_list[i].value;
}
const input_str = Object.entries(input_obj).map(item => item.join('=')).join('&'); // 至此转换的格式就是符合要求的格式。
...省略Ajax部分
return false;
}