原生Ajax实现异步通信
程序员文章站
2022-03-06 13:49:21
...
客户端:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="#" method="post">
用户名: <input type="text" name="username" id="username" onblur="onChang()">
<span id="spanUser"></span>
</form>
</body>
<script type="text/javascript" src="${pageContext.request.contextPath}/ajax/jquery/jquery-1.12.4.js"></script>
<%--<script src="jquery\jquery-1.12.4.js"></script>--%>
<script>
var xml=null;
function onChang() {
var username=$("#username").val();
if (username=="") {
$("#spanUser").html("<font color='red'>用户名不可以为空</font>")
}
else
{
//js实现异步请求
// 1、创建ajax异步请求的核心对象 xmlhttprequest
xml=createXmlHttpRequest();
// 2、设置请求参数
xml.open("post","/java92web/checkServlet")// xml.open("get","/java92web/checkServlet?name="+username)
xml.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
// 3、发送请求
var data="name="+username;
xml.send(data);
// 4、设置回调函数事件
xml.onreadystatechange=callback;
}
}
function callback() {
if (xml.readyState==4&&xml.status==200) {
//获取服务器相应内容
var data=xml.responseText;
if (data=="ok") {
$("#spanUser").html("<font color='red'>用户名已占用</font>")
}else
{
$("#spanUser").html("<font color='green'>√</font>")
}
}
}
function createXmlHttpRequest() {
if(window.XMLHttpRequest)
{
//标准浏览器
return new XMLHttpRequest();
}
else {
//低版本浏览器;
return new ActiveXObject('Microsoft.XMLHTTP');
}
}
</script>
</html>
服务器代码:
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/checkServlet")
public class checkServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String name=request.getParameter("name");
if (name.equals("admin")) {
out.print("ok");
}
else {
out.print("filed");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
下一篇: 利用Ajax实现简单的异步通信