我每次创建一个对象,都要这样复杂吗?如下代码:
JScript code:
"testAjax.htm" 文件:
首先声明一个保存 XMLHttpRequest 对象的 xmlHttp 变量。
然后使用 XMLHttp=new XMLHttpRequest() 来创建此对象。这条语句针对 Firefox、Opera 以及 Safari 浏览器。假如失败,则尝试针对 Internet Explorer 6.0 的 xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”),假如也不成功,则尝试针对 Internet Explorer 5.5 的 xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”)。
假如这三种方法都不起作用,那么这个用户所使用的浏览器已经太过时了,他或她会看到一个声明此浏览器不支持 AJAX 的提示。
可以不用这么麻烦,直接可以把这个函数的定义单独保存为一个js文件,在需要使用AJAX的页面中引用这个文件就可以了。
如下面详解的例子:
JScript code:
function CreateHTTPObject() { var xmlhttp; try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { xmlhttp = false; } } if (!xmlhttp && typeof XMLHttpRequest!='undefined') { try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp=false; } } if (!xmlhttp && window.createRequest) { try { xmlhttp = window.createRequest(); } catch (e) { xmlhttp=false; } } return xmlhttp;
}定义上面的函数,调用时创建实例即可,如下:
JScript code:
var xmlHttp = CreateHTTPObject(); if (!xmlHttp) { return; //无法创建 xmlhttp 对象 } xmlHttp.open("GET", url, true); xmlHttp.onreadystatechange = function(){HandleRequest(xmlHttp, "元素ID")}; xmlHttp.send(null);
也可以直接用jquery ,一句话搞定,如下代码:
$(document).ready(function(){ $("#userpass").blur(function(){ var password=$("#userpass").val(); var name=$("#username").val(); if(password==""||password==null){ $("#pass").html("请输入密码! "); b=false; }else if(!/^[a-zA-Z0-9_]{6,16}$/.test(password)){ $("#pass").html("输入格式不正确!密码应至少6为数字或字符 "); b=false; }else{ $.get("LoginAjaxPassword",{"userpass":encodeURI(encodeURI(password)),"username":encodeURI(encodeURI(name))},function(response){ $("#pass").html(response); if(response=="" "√" ""){ b=true; } }); } return b; }); $("#login-submit").click(function(){ var autologin=document.getElementById("autologin").checked; if(a&&b){ //if($("#autologin").attr("checked")==true){ if(autologin==true){ //${"#login-user-form"}.attr("action","AutoLogin"); //$("#login-user-form").submit(); document.form.action="AutoLogin"; document.form.submit(); }else{ //${"#login-user-form"}.attr("action","Login"); //$("#login-user-form").submit(); document.form.action="Login"; document.form.submit(); } } else{} }); });