XMLHttpRequest对象的原生创建与兼容处理
每次手动编写创建对象的代码是否过于繁琐?参考以下示例代码:
JScript code:
testAjax.htm 文件内容如下:
具体实现代码如下:
用户:
时间:
第一步是声明一个名为 xmlHttp 的变量,用于存储 XMLHttpRequest 实例。
接着执行 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简化AJAX请求实现
另一种更简便的方式是直接引入 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{}
});
});