Home >Web Front-end >JS Tutorial >Five steps for ajax requests

Five steps for ajax requests

angryTom
angryTomOriginal
2019-10-21 14:56:2649440browse

Five steps for ajax requests

Five steps of ajax request

The first step is to create an XMLHttpRequest object

The second step is to Register callback function

The third step is to configure the request information, open(), get

The fourth step is to send the request. Under the post request, put the parameters to be passed. This

The fifth step is to create a callback function

//第一步,创建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);
                });       
        }
}

Background method

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

This article is all here It’s over. For more other exciting content, you can pay attention to the JavaScript Video Tutorial column on the PHP Chinese website!

The above is the detailed content of Five steps for ajax requests. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn