微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AJAX数据传输原生js

原生ajax写法

<!DOCTYPE html>
<html lang="">

<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>
    <form>
        <p>
            <label for="">账户:</label>
            <input name="username" type="text">
        </p>
        <p>
            <label for="">密码</label>
            <input name="password" type="password">
        </p>
        <p>
            <button id="login" type="button">登录</button>
        </p>
    </form>
    <script>
        //查找元素
        var oLogin = document.getElementById(login);
        //事件
        oLogin.onclick = function () {
            //提取value值
            var username = document.querySelector(input[name=username]).value;
            var password = document.querySelector(input[name=password]).value;
           // console.log(username,password)
            //ajax
            var ajax = new XMLHttpRequest;
            ajax.open(POST,/user/login,true);
            //ajax.open(‘get‘,‘/user/list?pagesize=5&pageindex=1‘,true);
            //设置头部
            ajax.setRequestHeader(Content-type,application/x-www-form-urlencoded)
            //username=moz&password=123
            ajax.send(username= + username + &password= + password);
            //响应/回调函数
            ajax.onreadystatechange = function () {
                if(ajax.readyState==4){
                    var res=JSON.parse(ajax.responseText);
                    console.log(res);
                    if(res.status){
                        location.href=http://www.baidu.com;
                    }
                    else{
                        alert(res.msg);
                    }                  
                }
            }
        }

    </script>
    <script>
  //异步传输
// console.log(1) // setTimeout(function(){ // console.log(2) // },0) // console.log(3); </script> </body> </html>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐