ajax簡單創建代碼

/*
 *  XMLHttpRequest object
 */
var xmlHttp;
/*
 * Call back handler method
 */
var handlerMethod;
/*
 *  Response Data Type
 */
var responseDataType;

/*
 * Initial a XMLHttpRequest object when page load.
 */
window.οnlοad=pageLoad;
function pageLoad()
{
    createXmlHttp();
}

/*
 * Asynchronized send data to specified url
 * url:         the location to which date will be sent.
 * queryString: queryString data which will be sent to server.
 * method:      sending method, "GET" or "POST".
 * xml:         xml data which will be sent to server.
 * handler:     call back handle function.
 * type:        response data type, "Text" or "XML".
 */
function sendData(url,queryString,method,xml,handler,type)
{
    handlerMethod=handler;
    method = method.toUpperCase();
    responseDataType = type;
    if(method == "GET")
    {
        url = url + "?" + queryString;
    }
    xmlHttp.open(method,url,true);  
    xmlHttp.onreadystatechange = callback;
   
    if(xml)
    {
        xmlHttp.setRequestHeader("Content-Type","text/xml");
    }
    else if (method == "POST")
    {
        xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xml = queryString;
    }  
    xmlHttp.send(xml);
   
};

/*
 * Create and return a new XMLHttpRequest object
 */
function createXmlHttp()
{
    try
    {
        if (window.ActiveXObject)
        {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");   //IE6.0   
            if(!xmlHttp)
                 xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");   //IE 4.0,IE 5.0
        }
        else if (window.XMLHttpRequest)
        {
            xmlHttp = new XMLHttpRequest();     //supported by other browsers.
        }
    }
    catch(ex)
    {
        HandleException();
    }
   
    return xmlHttp;
};

/*
 * Handle create XMLHttpRequest exception.
 */
function HandleException()
{
    throw new Exception("XMLHttpRequest is not created!");
};

/*
 * Handle the response from server
 */
function callback()
{
    if(xmlHttp.readyState==4)
    {
        if(xmlHttp.status==200)
        {
            if(responseDataType != "Text")
            {
                handlerMethod(xmlHttp.responseXML);    //responseXML/Text is supposed by IE and Firefox,ResponseXML/Text only in IE     
            }
            else
            {
                handlerMethod(xmlHttp.responseText);
            }
        }
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章