AJAXデータ転送(オリジナルjs)

14664 ワード

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