企业免费建站,宝安做网站哪家好,php无版权企业网站管理系统,网站首页广告代码关于Ajax在之前的学习中#xff0c;已经对它的基础知识有了初步的了解。仅仅是欠实践。那么接下来就让实践来检验一下真理吧#xff01; 基础见#xff1a;http://blog.csdn.net/liu_yujie2011com/article/details/29812777 那么先回忆一下#xff0c;Ajax是用来解决什么问… 关于Ajax在之前的学习中已经对它的基础知识有了初步的了解。仅仅是欠实践。那么接下来就让实践来检验一下真理吧 基础见http://blog.csdn.net/liu_yujie2011com/article/details/29812777 那么先回忆一下Ajax是用来解决什么问题的答案非常easy解决同步和异步的问题。从而提高界面的友好型。增强用户体验。那么就结合“在加入用户时推断用户是否存在”的实例来体验一下吧。 一、HTML中input代码 tdwidth78%
inputnameuserId typetext classtext1iduserId
size10maxlength10 οnkeypressuserIdOnKeyPress()value%userId% οnblurvalidate(this)
spanidspanUserId/span
/td 二、Jsp界面代码 % pagelanguagejava contentTypetext/html; charsetGB18030pageEncodingGB18030%
% pageimportcom.bjpowernode.drp.sysmgr.manager.* %
%
StringuserIdrequest.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();//解决缓存方法用毫秒
varurluser_validate.jsp?userId trim(document.getElementById(userId).value) timenew Date().getTime();//设置请求方式用GET设置请求的URL。设置异步提交
xmlHttp.open(GET,url,true);//将方法地址复制给onreadystatechange属性
//相似于电话号码
xmlHttp.onreadystatechangecallback;//将设置的信息发送到Ajax引擎
xmlHttp.send(null);}else {
document.getElementById(spanUserId).innerHTML ;
}
} 三告诉Ajax引擎处理完后。我们通常指定一个方法句柄从而Ajax就会调用我们指定的方法。这样就能够得到Ajax引擎返回的数据回调机制。指定的方法例如以下 function callback(){
//Ajax引擎状态为成功
if(xmlHttp.readyState4){
//http协议状态为成功
if(xmlHttp.status200){
//alert(请求成功) //推断假设为空将红字span去掉 if(trim(xmlHttp.responseText) ! ){ document.getElementById(spanUserId).innerHTML font colorred xmlHttp.responseText /font }else{ document.getElementById(spanUserId).innerHTML ; } }else{ alert(请求失败错误码xmlHttp.status); } } } 四最后调用send方法把我们步骤设置的參数发给Ajax引擎去处理。这里指的就是步骤二的“xmlHttp.send(null)” 四、注意 以上就是对Ajax的一个简单实现但在这里还要注意几点 一使用Ajax技术须要清除缓存。否则easy产生莫名其妙的错误详细的方法有两种 1.採用URL后跟上时间戳产生随机数来防止浏览器缓存如 //解决缓存方法用毫秒 varurluser_validate.jsp?userId trim(document.getElementById(userId).value) timenew 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中的匿名函数来完毕推断用户时候存在的代码期待下一篇吧