get写法
// 1、创建xhr对象,ajax的基础:用户和服务器交换数据并且不会刷新整个页面,只会局部刷新
let xhr = new XMLHttpRequest()||new ActiveXObject("Microsoft.XMLHTTP");
//2、readystate 0-数据还未初始化 1-读取中 2-已读取 3-交互中 4-完成
xhr.onreadystatechange = function(){
console.log(xhr);
if(xhr.response=="no"){
span.innerHTML=`用户名不正确`;
span.style.color='red'
}else if(xhr.response=="ok"){
span.innerHTML=`用户名正确`;
span.style.color='green';
}
}
// 3\与服务器发起连接,传递需要的参数
xhr.open("get",`/checkUser.do?username=${username}`)
// 4\发送参数
xhr.send(null);
post请求写法
// 1、创建xhr对象,ajax的基础:用户和服务器交换数据并且不会刷新整个页面,只会局部刷新
let xhr = new XMLHttpRequest()||new ActiveXObject("Microsoft.XMLHTTP");
//2、readystate 0-数据还未初始化 1-读取中 2-已读取 3-交互中 4-完成
xhr.onreadystatechange = function(){
console.log(xhr);
if(xhr.readyState==4&&xhr.status==200){
if(xhr.response=="no"){
span.innerHTML=`用户名不正确`;
span.style.color='red'
}else if(xhr.response=="ok"){
span.innerHTML=`用户名正确`;
span.style.color='green';
}
}
}
// 3\与服务器发起连接,传递需要的参数
// xhr.open("get",`/checkUser.do?username=${username}`);
xhr.open("post",`/checkUser.do`);
//post请求需要设置请求头
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// 4\发送参数
// xhr.send(null);
xhr.send(`username=${username}`);