天天看點

JS實作Ajax---例:擷取伺服器時間

Ajax在本質上是一個浏覽器端的技術 XMLHttpRequest

XMLHttpRequest對象

XMLHttpRequest對象在IE浏覽器和非IE浏覽器中建立的方法不同。 簡而言之:它可以異步從伺服器端擷取txt或者xml資料

老版本IE: new ActiveXObject("Microsoft.XMLHTTP");

新版本浏覽器: new XMLHttpRequest();

為XMLHttpRequest對象設定請求參數

1.GET方式

1.1設定參數 xhr.open("GET", "GetAreasByAjax.ashx", true);

1.2GET方式請求可以設定浏覽器不使用緩存xhr.setRequestHeader("If-Modified-Since", "0");

1.3發送: xhr.send(null);//GET方式

2.POST方式:

1.1設定參數:xhr.open("POST", "GetAreasByAjax.ashx", true);

1.2添加請求頭:xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

回調函數

 判斷時注意,要:xhr.readyState == 4&&xhr.status == 200,不要xhr.status == 200&&xhr.readyState == 4

readyState屬性

readyState屬性指出了XMLHttpRequest對象在發送/接收資料過程中所處的幾個狀态。XMLHttpRequest對象會經曆5種不同的狀态。

0:未初始化。new完後;

1:已打開(已經初始化了)。對象已經建立并初始化,但還未調用send方法

2:已發送。已經調用send 方法,但該對象正在等待狀态碼和頭的傳回;

3:正在接收。已經接收了部分資料,但還不能使用該對象的屬性和方法,因為狀态和響應頭不完整;

4:已加載。所有資料接收完畢

XMLHttpRequest常用屬性

onreadystatechange 傳回或設定異步請求的事件處理程式

readyState 傳回狀态碼:0:未初始化;1:打開;2:發送;3:正在接收;4:已加載

responseText 使用字元串傳回HTTP響應

responseXML(xml對象,不是xml字元串) 使用XML DOM對象傳回HTTP響應,傳回的是一個對象,不是xml字元串。

通過ajax發起post請求時,需要注意的3點:

1.初始化的時候必須設定為post

xhr.open('post','url',true);

2.必須設定請求封包頭Content-Type的值為:application/x-www-form-urlencoded

xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');

3.如果有請求封包體,則在調用send()方法的時候,設定。

xhr.send('txtName=steve&gender=male&age=18');

案例

伺服器段代碼:

public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Clear();//清除之前的請求
            context.Response.Write(DateTime.Now.ToString("hh:mm:ss"));

            context.Response.End();//結束請求,防止相應其它内容
        }      

頁面代碼:

<body>
    <input id="btnPost" type="button" value="POST擷取伺服器時間" />
    <input id="btn" type="button" value="GET擷取伺服器時間" />
    <div id="div1" style="font-size:18px; color:red; font-weight:bolder;">

    </div>
</body>      

GET方式:

//确定事件
            document.getElementById('btn').onclick = function () {
                //JS實作Ajax步驟
                //1.建立XMLHttpRequest對象
                //1.1首先建立一個空對象
                var xhr = null;
                //1.2新浏覽器支援XMLHttpRequest    舊浏覽器(IE6)支援ActiveXObject
                //為了相容,判斷
                if (XMLHttpRequest) {
                    xhr = new XMLHttpRequest();
                } else if (ActiveXObject) {
                    //1.3别忘了重要的參數Microsoft.XMLHttp
                    xhr = new ActiveXObject("Microsoft.XMLHttp");
                }
                //2.設定回調函數
                xhr.onreadystatechange = function () {
                    //回調函數中有XMLHttpRequest的三個重要屬性
                    //xhr.readyState   有五種狀态0未初始化,1已打開,2已發送,3正在接收,4已加載
                    //xhr.status  傳回http狀态碼200表示成功
                    //xhr.responseText   這裡使用字元串傳回http響應 (相應方式多種)
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        document.getElementById('div1').innerHTML = xhr.responseText;
                    };
                }
                //3.初始化對象,三個參數,①請求方式get,post②請求的一般處理程式③bool(是否是異步請求)
                //解決緩存問題的兩種方法
                //方法一//随機數解決
                //xhr.open('get', 'Handler1.ashx?m='+Math.random(), true);
                //方法二,設定請求封包頭,,,在初始化完畢後,發起請求之前設定請求封包頭
                xhr.open('get', 'dd/Handler1.ashx', true);
                xhr.setRequestHeader('if-modified-since', '0');
                //4.發起請求   參數是請求封包體,,,get請求沒有請求封包體用null
                xhr.send(null);
            }//onclick
        }//onload      

POST方式:

//确認事件
            document.getElementById('btnPost').onclick = function () {
                var xhr = null;
                //POST請求
                //1.建立對象
                if (XMLHttpRequest) {
                    xhr = new XMLHttpRequest();
                } else if (ActiveXObject) {
                    xhr = new ActiveXObject("Microsoft.XMLHttp");
                }
                //2.設定回調函數
                xhr.onreadystatechange = function () {
                    //三個重要屬性
                    if (xhr.readyState==4 && xhr.status==200) {
                        document.getElementById('div1').innerHTML = xhr.responseText;
                    }
                }
                //3.初始化    三個參數
                xhr.open('post', 'dd/Handler1.ashx', true);
                //3.1post送出必須設定請求封包頭
                xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
                //4.發送請求,沒有請求封包體就寫null,
                //如果有請求封包體,則在調用send()方法的時候,設定。
                //xhr.send('txtName=steve&gender=male&age=18');
                xhr.send(null);
            }//onclick