﻿//Ajax类定义 
function AjaxHelper() 
{ 
    //构造函数 
    var httpRequest = null; 
    var requestResult = ""; 
    var sync = false; 
     
    this.init(); 
} 

//同步请求,默认为false 
AjaxHelper.prototype.sync=false; 

//初始化 
AjaxHelper.prototype.init = function() 
{ 
    try  
    { 
        httpRequest = new ActiveXObject("Msxml2.httpRequest"); 
    }  
    catch (e1)  
    { 
        try  
        { 
            httpRequest = new ActiveXObject("Microsoft.httpRequest"); 
        }  
        catch (e2)  
        { 
            try  
            { 
                httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
            }  
            catch (e3)  
            {
                httpRequest = null;                
            } 
        } 
    } 
     
    if(httpRequest == null) 
    { 
        alert("Error initializing AjaxHelper! Can't create XMLHttpRequest object."); 
    } 
} 

//发送请求 
AjaxHelper.prototype.request = function(url, postData) 
{ 
    var isPost = arguments.length > 1; 
    var method = isPost ? "POST" : "GET"; 
     
    httpRequest.open(method, url, this.sync); 
    httpRequest.onreadystatechange = createFunction(this, "handleResponse", this.requestCallback); 
    if(isPost) 
        httpRequest.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded"); 
        httpRequest.send(postData); 
} 

//处理请求结果 
AjaxHelper.prototype.handleResponse = function(callbackFunc) 
{ 
    if (httpRequest.readyState == 4) 
    { 
        if (httpRequest.status == 200) //正常 
        { 
            callbackFunc(httpRequest.responseText); 
        } 
        else if (httpRequest.status == 404) 
        { 
            alert("Request URL does not exist."); 
        } 
        else if (httpRequest.status == 403)  
        { 
            alert("Access denied."); 
        } 
        else 
        { 
            alert("Error: status code is " + httpRequest.status + "."); 
        } 
    } 
} 

//处理请求结果事件，需要客户端定义 
AjaxHelper.prototype.requestCallback = function(result){} 


//将有参数的函数封装为无参数的函数 
function createFunction(obj, funcName) 
{ 
    var args = []; 
    if(!obj) 
        obj = window; 

    for(var i=2; i<arguments.length; i++) 
        args.push(arguments[i]); 
         
    return function() 
    { 
        obj[funcName].apply(obj, args); 
    } 
}

