Ajax实践之用户是否存在

时间:2023-03-09 05:04:10
Ajax实践之用户是否存在

关于Ajax在之前的学习中,已经对它的基础知识有了初步的了解。仅仅是欠实践。

那么接下来就让实践来检验一下真理吧!

基础见:http://blog.****.net/liu_yujie2011com/article/details/29812777

那么先回忆一下,Ajax是用来解决什么问题的?答案非常easy:解决同步和异步的问题。从而提高界面的友好型。增强用户体验。那么就结合“在加入用户时推断用户是否存在”的实例来体验一下吧。

一、HTML中input代码

<tdwidth="78%">
<inputname="userId" type="text" class="text1"id="userId"
size="10"maxlength="10" onkeypress="userIdOnKeyPress()"value="<%=userId%>" onblur="validate(this)">
<spanid="spanUserId"></span>
</td>

二、Jsp界面代码

<%@ pagelanguage="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ pageimport="com.bjpowernode.drp.sysmgr.manager.*" %>
<%
StringuserId=request.getParameter("userId");
if(UserManager.getInstance().findUserById(userId) != null) {
out.println("用户代码已经存在");
}
%>

三、Javascript代码

(一)创建Ajax引擎对象XMLHttpRequest

    var xmlHttp;
functioncreateXMLHttpRequest() {
//表示当前浏览器不是ie,如ns,firefox
if(window.XMLHttpRequest){
xmlHttp= new XMLHttpRequest();
}else if (window.ActiveXObject) {
xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
}
}

(二)调用open方法与Ajax引擎建立连接,并告诉Ajax引擎我们的请求方式为get,请求url及採用异步方式

functionvalidate(field){
//alert(document.getElementById("userId").value);
//alert(field.value);
if(trim(document.getElementById("userId").value).length!= 0){
//创建Ajax核心对象XMLHttpRequest
createXMLHttpRequest(); //解决缓存方法,用毫秒
varurl="user_validate.jsp?userId=" +trim(document.getElementById("userId").value)+ "&time="+new Date().getTime(); //设置请求方式用GET,设置请求的URL。设置异步提交
xmlHttp.open("GET",url,true); //将方法地址复制给onreadystatechange属性
//相似于电话号码
xmlHttp.onreadystatechange=callback; //将设置的信息发送到Ajax引擎
xmlHttp.send(null); }else {
document.getElementById("spanUserId").innerHTML= "";
}
}

(三)告诉Ajax引擎处理完后。我们通常指定一个方法句柄,从而Ajax就会调用我们指定的方法。这样就能够得到Ajax引擎返回的数据(回调机制)。指定的方法例如以下:

function callback(){
//Ajax引擎状态为成功
if(xmlHttp.readyState==4){
//http协议状态为成功
if(xmlHttp.status==200){
//alert("请求成功! ")
//推断假设为空,将红字span去掉
if(trim(xmlHttp.responseText) != ""){
document.getElementById("spanUserId").innerHTML= "<font color='red'>" + xmlHttp.responseText +"</font>"
}else{
document.getElementById("spanUserId").innerHTML= "";
} }else{
alert("请求失败,错误码="+xmlHttp.status);
} }
}

(四)最后调用send方法把我们步骤设置的參数发给Ajax引擎去处理。这里指的就是步骤二的“xmlHttp.send(null)”

四、注意

以上就是对Ajax的一个简单实现,但在这里还要注意几点:

(一)使用Ajax技术须要清除缓存。否则easy产生莫名其妙的错误,详细的方法有两种:

1.採用URL后跟上时间戳(产生随机数)来防止浏览器缓存,如:

//解决缓存方法,用毫秒

varurl="user_validate.jsp?userId=" +trim(document.getElementById("userId").value)+ "&time="+new Date().getTime();

2.增加清除缓存代码,如:

header("Cache-Control:no-cache, must-revalidate");
xmlHttp.setRequestHeader("If-Modified-Since","0");
xmlHttp.setRequestHeader("Cache-Control","no-cache");

(二)假设须要提起多个请求,须要创建多个XMLHttpRequest对象。

五、总结

通过以上的步骤大家基本上了解了Ajax实践的基本流程,那么接下来就要通过使用JS中的匿名函数来完毕推断用户时候存在的代码,期待下一篇吧!