首页 > 解决方案 > 如何从 javascript 中的 addEventListener 内部发送 API 请求?

问题描述

我有一个 html 文件,我在其中创建了一些输入字段,从中收集用户的电子邮件和密码。然后我将这些值传递给一个 javascript 文件。我addEventListener()用来检测登录按钮的点击。在里面addEventListener()我调用了另一个函数,它基本上使用XMLHttpRequest(). 但似乎请求没有被发送到服务器。这是我的代码:

索引.html

<html>
  <script src="index.js"></script>
  <label>Email :</label>
  <input type="text" name="email" id="email" />
  <br /><br />
  <label>Password :</label>
  <input type="password" name="password" id="password" />
  <br /><br />
  <button type="submit" id="login">Login</button>
</html>

index.js

document.addEventListener("DOMContentLoaded", function() {
  var signin_btn = document.getElementById("login");
  signin_btn.addEventListener("click", function() {
    validate();
  });
});

function validate() {
  console.log("validate running.");
  var username = document.getElementById("email").value;
  var password = document.getElementById("password").value;
  console.log("username: ", username);

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      auth_token = JSON.parse(this.responseText)["token"];
      localStorage.setItem("auth_token", auth_token);
      console.log("auth from index.js: ", auth_token);
    }
    xhttp.open("POST", "http://127.0.0.1:5000/userauth/login", true);
    xhttp.setRequestHeader("Content-Type", "application/json");
    xhttp.send(JSON.stringify({ email: username, password: password }));
  };
}

当我运行此代码时,console.log("username: ", username);控制台中仅显示该部分。但console.log("auth from index.js: ", auth_token);不显示。似乎请求根本没有被执行。后端也没有显示错误。问题是什么?

标签: javascriptxmlhttprequestaddeventlistener

解决方案


您在函数内部编写了请求发送行,这是一个回调函数。validate()根据以下代码更改功能。


function validate() {
    console.log("validate running.");
    var username = document.getElementById("email").value;
    var password = document.getElementById("password").value;
    console.log("username: ", username);

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            auth_token = JSON.parse(this.responseText)["token"];
            localStorage.setItem("auth_token", auth_token);
            console.log("auth from index.js: ", auth_token);
        }
    };
    xhttp.open("POST", "http://127.0.0.1:5000/userauth/login", true);
    xhttp.setRequestHeader("Content-Type", "application/json");
    xhttp.send(JSON.stringify({ email: username, password: password }));
}


推荐阅读