xmlhttp對象的簡單封裝

xmlhttp對象好用,但是一個頁面如果有很多次調用的話,寫起來也很麻煩,所以,這裏簡單封裝了一下,可以作爲對象來調用
ajax.js:
function ajaxsz() {
    var xmlHttp;
    if(window.XMLHttpRequest) {   
       xmlHttp = new XMLHttpRequest();
   }
   else if(window.ActiveXObject) {
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");  
    }
    this.rep = xmlHttp;
    this.sendData = function(method,URL,asy,fun) {
        if (asy)//異步
        {
            xmlHttp.onreadystatechange = function(){//此處檢測狀態,知道符合要求時,纔會執行事件             
             if(xmlHttp.readyState==4 && xmlHttp.status == 200){
        fun(xmlHttp);
             }            
           }
            if(method == "POST") {
                xmlHttp.open("POST",URL,true);
                xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                xmlHttp.send(null);
            }
            else {
                 xmlHttp.open("GET",url,true);
                 xmlHttp.send(null);
            }
        }   
        else {
            if(method == "POST") {
                xmlHttp.open("POST",URL,false);
                xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                xmlHttp.send(null);
            }
            else {
                xmlHttp.open("GET",url,false);
                xmlHttp.send(null);
            }
            return xmlHttp;
        }  
    }
}

服務器端簡單處理:
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request["UserName"]))
            {
                Response.Write("您好!" + Request["UserName"]);
            }
            else
            {
                Response.Write("您好!");
            }
        }

調用頁面:
<html>
<head>
    <title>Ajax測試頁</title>
    <script type="text/javascript" src="js/ajax.js" language="javascript"></script>
    <script language="javascript" type="text/javascript">
    function getStr(){
        var userName = document.getElementById("Text1").value;
        var myajax = new ajaxsz();
        myajax.sendData("POST","http://localhost:5964/GetData/GetString.aspx?UserName=" + userName,true,aa);
    }    
    function aa(xmlhttp)
    {
        document.getElementById("mystr").innerHTML = xmlhttp.responseText;
    }
    </script>
</head>
<body style="font-size: 14px" text="#6600ff">
        <div style="margin:0px auto">
            返回字符串<br />
            &nbsp;<br />
            <div id="mystr" style="width: 121px; height: 34px">
            </div>
            輸入您的姓名<input id="Text1" style="width: 125px" type="text" />
            <input id="Button1" type="button" value="GetString" οnclick="getStr()" />
        </div>
</body>
</html> 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章