ajax的post封装

2019-08-26  本文已影响0人  成长储存罐

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Document</title>

</head>

<body>

        <input type="text" name="" value="" id="a">

        <input type="text" name="" value="" id="b">

        <input type="button" name="" value="传输" id="btn">

</body>

<script>

    var oa = document.getElementById("a");

    var ob = document.getElementById("b");

    var obtn = document.getElementById("btn");

obtn.onclick = function(){

        var url = "http://localhost/1907/ajax/post.php";

        ajaxPost(url,function(res){

            console.log(res)

        },{

            user:oa.value,

            pass:ob.value

        })

    }

    function ajaxPost(url,cd,date){

        date=date||{};

        var str="";

        for(var i in date){

            str+=`${i}=${date[i]}&`

        }

        var d=new Date();

        url=url+"?"+'zssz='+d.getTime();

        var xhr = new XMLHttpRequest();

        xhr.open("post",url)

        xhr.onreadystatechange = function(){

            if(xhr.readyState == 4 && xhr.status == 200){

                cd(xhr.responseText)

            }

        }

        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

        xhr.send(str);

    }

</script>

</html>

上一篇 下一篇

猜你喜欢

热点阅读