ajax学习笔记02-POST的基本使用

一、使用ajax发送post请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>07-ajax-post</title>
    <!--
    1.什么是ajax
    ajax是与服务器交换数据并更新部分网页的艺术,在不重新加载整个网页的情况下更新数据
    -->
    <script>
        window.onload = function (ev) {
            var oBtn = document.querySelector("button");
            oBtn.onclick = function (ev1) {
                //1.创建一个异步对象
                var xmlhttp = new XMLHttpRequest();
                //2.设置请求方式和请求地址
                /*
                *   method:请求的类型;GET 或 POST
                    url:文件在服务器上的位置
                    async:true(异步)或 false(同步)
                * */
                xmlhttp.open("POST", "07-ajax-post.php", true);
                //以下代码需要放到open和send之间
                xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                //3.发送请求
                xmlhttp.send("username=doudou&passwd=123456");
                //4.监听状态变化
                xmlhttp.onreadystatechange = function (ev2) {
                    /*
                    0: 请求未初始化
                    1: 服务器连接已建立
                    2: 请求已接收
                    3: 请求处理中
                    4: 请求已完成,且响应已就绪
                    */
                    if (xmlhttp.readyState === 4){
                        //判断是否请求成功,xmlhttp.status返回的http状态码
                        if(xmlhttp.status >= 200 && xmlhttp.status < 300 ||
                            xmlhttp.status ===304){
                            //5.处理返回结果
                            alert(xmlhttp.responseText);
                            console.log(xmlhttp.responseText);
                        }

                    }
                }

            }
        }
    </script>
</head>
<body>
<button>发送请求</button>
</body>
</html>

二、封装ajax请求

function ajax(option) {
    /*
    type:请求类型
    * url:请求地址
    * obj:请求数据对象
    * timeout:请求超时时间
    * success:请求成功时的回调
    * error:请求失败时的回调
    * */
    //0.格式化obj
    function obj2str(data) {
        option.data.t = new Date().getTime();
        var res = [];
        for (var key in option.data){
            //encodeURIComponent()将请求中的中文进行重新编码
            res.push(encodeURIComponent(key)+ "=" + encodeURIComponent(option.data[key]));
        }
        return res.join("&")

    }
    //1.创建一个异步对象
    var xmlhttp;
    //判断浏览器是否支持XMLHttpRequest
    if (window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }
    else
    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //2.设置请求方式和请求地址
    /*
    *   method:请求的类型;GET 或 POST
        url:文件在服务器上的位置
        async:true(异步)或 false(同步)
    * */
    var str = obj2str(option.data);
    if (option.type.toLocaleLowerCase() === "get"){
        //+ "?t=" + (new Date().getTime())兼容浏览器
        xmlhttp.open("GET",option.url + "?" + str,true);
        //3.发送请求
        xmlhttp.send();
    }
    else {
        xmlhttp.open("POST", option.url, true);
        //以下代码需要放到open和send之间
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        //3.发送请求
        xmlhttp.send(str);
    }

    //4.监听状态变化
    xmlhttp.onreadystatechange = function (ev2) {
        /*
        0: 请求未初始化
        1: 服务器连接已建立
        2: 请求已接收
        3: 请求处理中
        4: 请求已完成,且响应已就绪
        */
        if (xmlhttp.readyState === 4) {
            //关闭定时器
            clearInterval(timer);
            //判断是否请求成功,xmlhttp.status返回的http状态码
            if (xmlhttp.status >= 200 && xmlhttp.status < 300 ||
                xmlhttp.status === 304) {
                //5.处理返回结果
                option.success(xmlhttp);
            }else {
                option.error(xmlhttp)
            }
        }
    };
    if (option.timeout){
        //请求响应时间等于timeout时,中断请求,关闭定时器
        timer = setInterval(function () {
            console.log("中断请求");
            xmlhttp.abort();
            //关闭定时器
            clearInterval(timer);
        }, option.timeout);
    }
}

三、调用ajax post请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>08-ajax-jquery</title>
    <script src="myAjax2.js"></script>
    <!--<script src="../jquery-1.12.4.js"></script>-->
    <script>
        window.onload = function (ev) {
            var oBtn = document.querySelector("button");
            oBtn.onclick = function (ev1) {
                ajax({
                        type:"post",
                        url:"07-ajax-post.php",
                        data:{
                            "username":"doulihang",
                            "passwd":"444444"
                        },
                        timeout:3000,
                        success:function (xhr) {
                            alert(xhr.responseText)
                        },
                        error:function (xhr) {
                            alert("请求失败")
                        }
                })
            }
        }
    </script>

</head>
<body>
<button>发送请求</button>
</body>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值