原生JS利用XMLHttpRequest实现Get和Post请求

之前用jQuery的时候经常使用$.ajax()方法发送请求,由于最近一直在捣鼓原生JS,所以对XMLHttpRequest作了一番研究,下面看一个例子:输入两个数,计算他们的和,这里使用XMLHttpRequest实现。
在这里插入图片描述
Get请求代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>测试</title>
</head>
<body>
    <input id="num_one" type="text" /> + <input id="num_two" type="text" /> = <input id="num_res" type="text" /> 
    <button id="btn">计算</button>
    <script>
        document.getElementById('btn').onclick = function () {
            getData();
        }

        function getData() {
            // 获取数据
            var num_one = document.getElementById('num_one').value;
            var num_two = document.getElementById('num_two').value;
            var url = 'ashx/TestHandler.ashx?num_one=' + num_one + '&num_two=' + num_two;

            // 发送请求
            var xhr = new XMLHttpRequest();
            xhr.open('get', url);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    document.getElementById('num_res').value = xhr.responseText;
                }
            }
            xhr.send();
        }
    </script>
</body>
</html>

Post请求代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>测试</title>
</head>
<body>
    <input id="num_one" type="text" /> + <input id="num_two" type="text" /> = <input id="num_res" type="text" /> 
    <button id="btn">计算</button>
    <script>
        document.getElementById('btn').onclick = function () {
            postData();
        }
        function postData() {
            // 获取数据
            var num_one = document.getElementById('num_one').value;
            var num_two = document.getElementById('num_two').value;
            var url = 'ashx/TestHandler.ashx?num_one=' + num_one + '&num_two=' + num_two;

            // 发送请求
            var xhr = new XMLHttpRequest();
            xhr.open('post', url);
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    document.getElementById('num_res').value = xhr.responseText;
                }
            }
            xhr.send();
        }
    </script>
</body>
</html>

后台代码:

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

namespace WebApplication1.ashx
{
    /// <summary>
    /// TestHandler 的摘要说明
    /// </summary>
    public class TestHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            int num_one = int.Parse(context.Request["num_one"].ToString());
            int num_two = int.Parse(context.Request["num_two"].ToString());

            context.Response.Write((num_one + num_two).ToString());
        }

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

这里需要注意:xhr.readyState表示XMLHttpRequest对象的状态:
0:未初始化。对象已创建,未调用open;
1:open方法成功调用,但Sendf方法未调用;
2:send方法已经调用,尚未开始接受数据;
3:正在接受数据。Http响应头信息已经接受,但尚未接收完成;
4:完成,即响应数据接受完成。
xhr.status服务器返回的http状态码:
200:表示“成功”;
404:表示“未找到”;
500:表示“服务器内部错误”等。
xhr.responseText表示后台返回的结果

发布了99 篇原创文章 · 获赞 16 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/HerryDong/article/details/103973866
今日推荐