首頁 > web前端 > js教程 > 主體

ajax請求的五個步驟

angryTom
發布: 2019-11-23 17:24:28
原創
49358 人瀏覽過

ajax請求的五個步驟

ajax請求的五個步驟   

#第一步,建立XMLHttpRequest物件

##第二步,註冊回呼函數


第三步,配置請求訊息,open(),get


#第四步,發送請求,post請求下,要傳遞的參數放這


第五步,建立回呼函數


//第一步,创建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);
        }
登入後複製

這篇文章到這裡就已經全部結束了,更多其他精彩內容可以關注PHP中文網的

JavaScript影片教學專欄!

以上是ajax請求的五個步驟的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!