原生js发送请求

const loginForm = document.querySelector('#loginForm');
const loginName = document.querySelector('#loginName');
const loginPwd = document.querySelector('#loginPwd');

loginForm.addEventListener('submit', function (e) {
        e.preventDefault();
        const name = loginName.value;
        const pwd = loginPwd.value;
        const xhr = new XMLHttpRequest();

        xhr.addEventListener('load', function () {
            const data = JSON.parse(xhr.responseText);
            if (data.code === 1) {
                location.href = '/';
            }
            else {
                alert(data.message);
            }
        });

        xhr.open('POST', '/mide/student/api/login');
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.send(JSON.stringify({
            loginName: name,
            loginPwd: pwd
        }));
    })

此为登录HTML请求

form表单submit 自带发送请求事件

e.preventDefault();

在事件中加入   可 阻止此事件

posted @ 2018-10-12 09:23  Eunuch_Li  阅读(299)  评论(0编辑  收藏  举报