Ajax基础(检查用户名是否存在)

前端之家收集整理的这篇文章主要介绍了Ajax基础(检查用户名是否存在)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
<----------------------客户端:register.jsp文件--------------------------->
<script type="text/javascript">
var req;
function validate(){
var idField = document.getElementByIdx_x_x_x_x_x("userid");
var url = "validate.jsp?name="+ escape(idField.value);//把userid的值转换为url中格式传到validate.jsp中
if(window.XMLHttpRequest){
req = new XMLHttpRequest();
}else if(window.ActiveXobject){
req = new ActiveXobject("Microsoft.XMLHTTP");
}
req.open("get",url,true);//get是使用get()方法,url是要浏览的网页, true是代表使用异步模式
<%--
readystate是代表网页的状态
readystate = 0 为 UNINITIALIZED;OPEN NOT YET CALLED
readystate = 1 为 LOADING ; SEND FOR REQUEST NOT YET CALLED
readystate = 2 为 LOADED;SEND CALLED,HEADERS AND STATUS ARE AVAILABLE
readystate = 3 为 INTERACTIVE RESPONSE,RESPONSETEXT ONLY PARTIALLY SET
readystate = 4 为 COMPLETED:FINISHED DOWNLOADING RESPONSE
--%>
req.onreadystatechange = callback;
req.send(null);
}
function callback(){
if(req.readyState == 4){ //判断请求是否已结束
if(req.status == 200) //判断请求的页面是否正确
// alert(req.responseText); //打印出服务端反馈的信息
var msg = req.responseXML.getElementsByTagName_r("msg")[0];
setMsg(msg.childNodes[0].nodeValue);
}
}
function setMsg(msg){
if(msg == "invalidate"){
document.getElementByIdx_x("usermsg").innerHTML = "<font color='red' > 用户名已存在</font>";
}else{
document.getElementByIdx_x("usermsg").innerHTML = "<font color='green'> 可以注册</font>";
}
}
</script>

<-------------------------------服务端:validate.jsp文件-------------------------------->
<%@ page import = "com.gdlg.shopping.User" %>
<%
String username = request.getParameter("name");

User u = new User();
boolean flag = u.userExist(username.trim());
System.out.println(username.trim());

response.setContentType("text/xml");
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader("Exspires",0);

if(flag==true){
response.getWriter().write("<msg>invalidate</msg>");
}else{
response.getWriter().write("<msg>validate</msg>");
}
%>
原文链接:https://www.f2er.com/ajax/166011.html

猜你在找的Ajax相关文章