后台代码:
前端页面:
<script>
//1.给用户名 输入框绑定 失去焦点事件
document.getElementById("username").onblur=function(){
//2. 发送ajax请求
//获取用户名的值
var username=this.value;
//2.1创建核心对象
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//2.2发起请求
xhttp.open("GET", "http://localhost:8080/test/selectUserServlet="+username);
xhttp.send();
//2.3获取响应
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//alert( this.responseText);
//判断
if(this.responseText=="true"){
//用户名存在显示提示信息
document.getElementById("username_err").style.display='';
}else{
//用户不存在,清除提示信息
document.getElementById("username_err").style.display='none';
}
}
};
};
</script>
后台返回标记,前端发送ajax请求和username的数据,然后处理响应显示在页面上。
顺便提一下无法引用css外部样式啊,网上找了一个多小时全是没用的帖子。
现在说一下解决方法
给css目录标记为Sources Root 就行了
下面讲一下ajax的框架axios
第一步就是导入axios的包,然后写一个页面
因为没有服务器资源所以我们创建一个servlet
这里的.then函数是异步函数,里面接收一个回调函数,resp是一个对象,然后弹出这个对象的数据。
下面来演示一遍