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>

相关文章

$.AJAX()方法中的PROCESSDATA参数 在使用jQuery的$.ajax()方...
form表单提交的几种方式 表单提交方式一:直接利用form表单提...
文章浏览阅读1.3k次。AJAX的无刷新机制使得在注册系统中对于...
文章浏览阅读1.2k次。 本文将解释如何使用AJAX和JSON分析器在...
文章浏览阅读2.2k次。/************************** 创建XML...
文章浏览阅读3.7k次。在ajax应用中,通常一个页面要同时发送...