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);
            }
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值