javascript - 使用 NodeJS 的单页应用程序
问题描述
我在单页应用程序中尝试做的是,每当单击登录按钮时,它都会使用 XMLHttpRequest 从 nodejs 服务器获取 html 表单,然后将其显示在显示区域中。填写表单并单击按钮后,它会再次从服务器获取其他 HTML 表单。以下是代码:
document.addEventListener('DOMContentLoaded', () => {
const login = document.querySelector("#login");
const displayArea = document.querySelector("#displayArea");
login.onclick = () => {
loginPage('GET', '/login');
};
const loginPage = (method, url) => {
let xml = new XMLHttpRequest();
xml.open(method, url);
xml.onload = () => {
let loadPage = JSON.parse(xml.responseText);
document.title = loadPage.title;
displayArea.innerHTML = loadPage.form;
const submit = document.querySelector("#submit");
submit.onclick = (e) => {
e.preventDefault();
loginAuth();
};
};
xml.send();
};
const loginAuth = () => {
const username = document.querySelector("#username");
const password = document.querySelector("#password");
let auth = {
username: username.value,
password: password.value
};
let url = "/login/" + JSON.stringify(auth);
const xml = new XMLHttpRequest();
xml.open('POST', url);
xml.onload = () => {
let loadPage = JSON.parse(xml.responseText);
document.title = loadPage.title;
displayArea.innerHTML = loadPage.form;
};
xml.send();
};});
由于表单数据在调用函数之外不可用/不可见,因此挑战是如果我继续在函数中获取 HTML 表单,它将是一个嵌套函数调用。我该如何避免这种情况?有没有简单的出路?
谢谢你的帮助!
解决方案
推荐阅读
- javascript - 如何在 jQuery 过滤器中设置日期的默认值
- node.js - Flow 和 webpack 别名
- regex - 在 Dart 正则表达式中匹配 $(美元符号)单词
- ipfs - 为什么 IPFS 在初始化节点时会生成 RSA 密钥对?
- c# - OrientDB 重试模式异常
- java - 如何从 Jackson @JsonCreator 构造函数访问 Spring Boot 环境变量
- angular - 输入的 Angular 格式 ViewModel 不改变模型值
- ios - 可可豆荚安装
- r - 在 r 中对观察进行子集化时出现意外错误“=”
- mule - 文件存在于 mulesoft 中