XMLHttpRequest Ajax 简洁优雅的js + ajax代码

首先创建一个XMLHttpRequest

function createRequest()
{
    try
    {
        request = new XMLHttpRequest();
    }
    catch(trymicrosoft)
    {
        try
        {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(othermicrosoft)
        {
            try
            {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(failed)
            {
                request = null;
            }
        }
    }
    if(request == null)
    {
        alert("Error,Creating request object!");
    }
}

然后开始编写需要发送异步请求的方法:

function ajaxLogin()
{
    var emailLogin = document.getElementById("UserEmailInput").value;
    var passwordLogin = document.getElementById("UserPwdInput").value;

    createRequest();
    //new Date().getTime() 加上一个随机时间字符,避免请求缓存
    var url = "AjaxLogin.aspx?Email=" + emailLogin + "&thisTime=" + new Date().getTime();
    request.open("GET",url,true);
    request.onreadystatechange = updatePageUserLogin; //回调函数updatePageUserLogin方法名后面被禁止书写小括号()
    request.send(null);
}

回调函数执行:

function updatePageUserLogin()
{
    if(request.readyState == 4)
    {
        if(request.status == 200)
        {
            var content = request.responseText;
            if(content == "True")
            {
                //alert("登录成功");
                setUserLoginOkCookie(); //用户登录成功以后给用户保存cookie
            }

            if(content == "False")
            {
                //alert("失败");
                var html = '<div style="color:"><img src="pic/bg/exit.png"></img> 用户名或密码错误,请重新输入:</div>';
                jQuery("#LoginNameAndPasswordError").html(html);
            }

        }
    }
}