原生Ajax异步向后端发http请求(post,get方法区别)——原生JS代码示例

版权声明:随便转载,互相学习,注明来源即可,不想注明也没事 https://blog.csdn.net/yangwohenmai1/article/details/89186670

GitHub源码下载地址:https://github.com/yangwohenmai/TEST/tree/master/WebText

前端原生ajax发请求的代码,通过xmlhttp的方法操作,重点全在代码注释里。

有post和get两种方法,

<script>
    setTimeout('CommentAll()', 5000);
    var xmlHttp = new XMLHttpRequest();


    function CommentAll() {
        //第二步,注册回调函数
        debugger
        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,open方法也可以在在这里传参
        xmlHttp.open("post", "/xmlHttpTest.ashx?methodName=GetAllComment1", true);

        //post请求下需要配置请求头信息,必须配置,不配置的话后端接受不到参数,智能接受到url中带的参数
        //(PS:测试发现,在ashx事件响应模式中接受不到,但是asp.net是可以接收到的)
        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        //第四步,发送请求,post请求下,要传递的参数放这里,get方法不用传参数
        //如果是xmlHttp.open("get".......)方法,可以直接写xmlHttp.send(null)
        xmlHttp.send("methodName=GetAllComment&str1=str1&str2=str2");

    }
    //第五步,创建回调函数
    function callback1() {
        //4状态代表后台数据已经处理完成
        if (xmlHttp.readyState == 4)
            if (xmlHttp.status == 200) {
                //取得返回的数据
                var data = xmlHttp.responseText;
                //json字符串转为json格式
                alert(data);
            }
    }

</script>

后端使用的是最简洁的ashx响应式文件,对于如何获取前端传来的参数,参考下面这个链接:

 https://bbs.csdn.net/topics/391839936?page=1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebText
{
    public class xmlHttpTest : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = System.Web.HttpContext.Current.Request;
            string methodName1 = System.Web.HttpContext.Current.Request.QueryString["methodName"];
            string methodName = context.Request["methodName"];
            string methodNameForm = System.Web.HttpContext.Current.Request.Form["methodName"];
            string str1 = System.Web.HttpContext.Current.Request.Form["str1"];
            string str2 = context.Request["str2"];
            Uri Project_Id = request.UrlReferrer;
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello World");
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 顺便科普一个post和get的区别和使用场景:

https://blog.csdn.net/lhjuejiang/article/details/79470245

猜你喜欢

转载自blog.csdn.net/yangwohenmai1/article/details/89186670