原生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>