javascript - 如何从 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);
不显示。似乎请求根本没有被执行。后端也没有显示错误。问题是什么?
解决方案
您在函数内部编写了请求发送行,这是一个回调函数。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 }));
}
推荐阅读
- javascript - 我如何“提示”提交按钮,以便当我填写表格并单击输入时它会提示它?)(仅在 JavaScript 中完成,没有 HTML/CSS 或 PHP)
- mysql - mysql合并连接表中的空值
- javascript - node.js 多个 __dirnames
- django - Djstripe - Stripe webhook 404 错误:如何解决?
- python - Python中的混合字符串
- reactjs - React Native 保存旧的文本输入数据
- visual-studio-code - SFML - VScode - CMAKE 项目 - 项目运行良好,但标题上出现曲线
- mysql - MySQL - 不和谐 - 发布表/结果
- javascript - 如何将脚本移动到 div 容器中
- apache-kafka - 如何在不重新部署的情况下让 Flink 作业生成可变数量的 Kafka 主题?