原生ajax請求的五個步驟


//第一步,創建XMLHttpRequest對象
var xmlHttp = new XMLHttpRequest();
function CommentAll() {
    //第二步,注冊回調函數
    xmlHttp.onreadystatechange =callback1;
    //{
    //    if (xmlHttp.readyState == 4)
    //        if (xmlHttp.status == 200) {
    //            var responseText = xmlHttp.responseText;

    //        }
    //}
    //第三步,配置請求信息,open(),get
    //get請求下參數加在url后,.ashx?methodName = GetAllComment&str1=str1&str2=str2
    xmlHttp.open("post", "/ashx/myzhuye/Detail.ashx?methodName=GetAllComment", true);

    //post請求下需要配置請求頭信息
    //xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    //第四步,發送請求,post請求下,要傳遞的參數放這
    xmlHttp.send("methodName = GetAllComment&str1=str1&str2=str2");//"

}
//第五步,創建回調函數
function callback1() {
    if (xmlHttp.readyState == 4)
        if (xmlHttp.status == 200) {
            //取得返回的數據
            var data = xmlHttp.responseText;
            //json字符串轉為json格式
            data = eval(data);
            $.each(data,
                function(i, v) {
                    alert(v);
                });       
        }
}



//后台方法
 private  void GetAllComment(HttpContext context)
        {

            //Params可以取得get與post方式傳遞過來的值。
            string methodName = context.Request.Params["methodName"];

            //QueryString只能取得get方式傳遞過來的值。
            string str1 = context.Request.Form["str1"];

            //取得httpRequest傳來的值,包括get與post方式
            string str2 = context.Request["str2"];

            List<string> comments = new List<string>();

            comments.Add(methodName);

            comments.Add(str1);

            comments.Add(str2);


            //ajax接受的是json類型,需要把返回的數據轉給json格式
            string commentsJson = new JavaScriptSerializer().Serialize(comments);
            context.Response.Write(commentsJson);
        }

 

上面是代碼,那簡單總結下如下,要完整實現一個AJAX異步調用和局部刷新,通常需要以下幾個步驟:

      (1)創建XMLHttpRequest對象,也就是創建一個異步調用對象.

      (2)創建一個新的HTTP請求,並指定該HTTP請求的方法、URL及驗證信息.

      (3)設置響應HTTP請求狀態變化的函數.

      (4)發送HTTP請求.

      (5)獲取異步調用返回的數據.

      (6)使用JavaScript和DOM實現局部刷新.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM