如何通过函数参数发送POST数据?

问题描述

我正在尝试将数据从登录表单传递给函数。 如果我直接尝试使用它有效的数据,例如:

xhr.send(JSON.stringify({
    email: 'george.bluth@reqres.in',password: 'password'
}));

我正在尝试使用用户在表单中键入的内容而不是固定数据来执行此操作,然后当用户单击登录按钮时,它将运行代码。我已经检查了数据,没问题,但它不起作用。可能是时间问题

代码

var loginButton = document.getElementById("login-button");
    
    loginButton.addEventListener("click",function(e){
        var email = document.getElementById("email").value;
        var senha = document.getElementById("senha").value;
        login(email,senha);
    },false);
    
    function login(email,password) {
        var xhr = new XMLHttpRequest();
        xhr.open("POST","https://reqres.in/api/login",true);
        xhr.setRequestHeader('Content-Type','application/json');
        xhr.send(JSON.stringify({
            email: email,password: password
        }));
        xhr.onload = function () {
            document.querySelectorAll('.entrar')[0].style.display = 'none';
            document.querySelectorAll('.smooth-spinner')[0].style.display = 'block';
    
            if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
                window.location.href = "/pages/lista-usuarios.html";
            }
    
            console.log(this.responseText);
            var data = JSON.parse(this.responseText);
            console.log(data);
        }
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)