首页 > 解决方案 > 使用 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 表单,它将是一个嵌套函数调用。我该如何避免这种情况?有没有简单的出路?

谢谢你的帮助!

标签: javascripthtmlnode.js

解决方案


推荐阅读