Ajax 通过异步请求,可以在整体网页不刷新的情况下,发起异步请求,实现局部刷新,下面是一个 简单的在输入用户名后, 检查 用户名是否存在的案例;
jsp代码
<body>
username : <input id="name" name="username" οnblur="checkName();" /> <span id="msg" style="color: red"></span>
</body>
script 代码
<script type="text/javascript">
function checkName(){
var name = document.getElementById("name").value;
// 创建 XMLHttpRequest 对象
var xhr;
if(window.XMLHttpRequest){ //chrome window.XMLHttpRequest 为真 ie 为 假
xhr = new XMLHttpRequest(); //chrome 浏览器
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP"); //IE
}
//Get方式发送请求
//xhr.open("GET", "CheckName?username="+name);
//xhr.send(null);
//POST 方式发送请求, post方式不能利用url传数据, 需要模拟表单 用 key-value传递
xhr.open("POST", "CheckName"); //CheckName 为servlet的url
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded") //模拟表单的 enctype 属性
xhr.send("username="+name);
//监听响应
xhr.onreadystatechange = function(){
if(xhr.readyState== 4 && xhr.status == 200){ //请求状态码为4 表示成功响应,200表示响应正确
var span = document.getElementById("msg");
span.innerHTML = xhr.responseText;
}
}
}
</script>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = (String) request.getParameter("username");
//这句话的意思,是让浏览器用utf8来解析返回的数据
response.setHeader("Content-type", "text/html;charset=UTF-8");
//这句话的意思,是告诉servlet用UTF-8转码,而不是用默认的ISO8859
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
//模拟dao 层的数据库查询
if("liu".equals(name)){
//out.println("your name has existed !");
out.println("你的用户名已存在!");
}else{
out.println("your name is ok!");
}
out.flush();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
效果