1. 程式人生 > >原生ajax請求的五個步驟

原生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); }