我如何使香草 js 中的弹出功能正常工作,并从节点 js 获取响应?

问题描述 投票:0回答:0

所以在多次搜索和论坛后,我尝试为项目编写这段代码(这是我的第一个主要项目)。在这里,我试图接受从 html 到 vanilla js 的表单输入,然后将它发送到后端 nodejs。我使用路由作为不同的方法调用来处理接收到的数据。我使用的数据库是 postgreSQL。 然后检查响应数据以显示不同的弹出窗口。

下面的代码是 main.js 是日历,用于获取所需/期望的日期作为检查该特定日期的手段。其他数据从 html 表单中接受。

(function($) {

    "use strict";

    document.addEventListener('DOMContentLoaded', function(){
    var today = new Date(),
        year = today.getFullYear(),
        month = today.getMonth(),
        monthTag =["January","February","March","April","May","June","July","August","September","October","November","December"],
        day = today.getDate(),
        days = document.getElementsByTagName('td'),
        selectedDay,
        setDate,
        daysLen = days.length;
// options should like '2014-01-01'
    function Calendar(selector, options) {
        this.options = options;
        this.draw();
    }
    

    
    Calendar.prototype.draw  = function() {
        this.getCookie('selected_day');
        this.getOptions();
        this.drawDays();
        var that = this,
            reset = document.getElementById('reset'),
            pre = document.getElementsByClassName('pre-button'),
            next = document.getElementsByClassName('next-button');
            
            pre[0].addEventListener('click', function(){that.preMonth(); });
            next[0].addEventListener('click', function(){that.nextMonth(); });
            reset.addEventListener('click', function(){that.reset(); });
        while(daysLen--) {
            days[daysLen].addEventListener('click', function(){that.clickDay(this); });
        }
    };
    
    Calendar.prototype.drawHeader = function(e) {
        var headDay = document.getElementsByClassName('head-day'),
            headMonth = document.getElementsByClassName('head-month');

            e?headDay[0].innerHTML = e : headDay[0].innerHTML = day;
            headMonth[0].innerHTML = monthTag[month] +" - " + year;        
     };
    
    Calendar.prototype.drawDays = function() {
        var startDay = new Date(year, month, 1).getDay(),

            nDays = new Date(year, month + 1, 0).getDate(),
    
            n = startDay;

        for(var k = 0; k <42; k++) {
            days[k].innerHTML = '';
            days[k].id = '';
            days[k].className = '';
        }

        for(var i  = 1; i <= nDays ; i++) {
            days[n].innerHTML = i; 
            n++;
        }
        
        for(var j = 0; j < 42; j++) {
            if(days[j].innerHTML === ""){
                
                days[j].id = "disabled";
                
            }else if(j === day + startDay - 1){
                if((this.options && (month === setDate.getMonth()) && (year === setDate.getFullYear())) || (!this.options && (month === today.getMonth())&&(year===today.getFullYear()))){
                    this.drawHeader(day);
                    days[j].id = "today";
                }
            }
            if(selectedDay){
                if((j === selectedDay.getDate() + startDay - 1)&&(month === selectedDay.getMonth())&&(year === selectedDay.getFullYear())){
                days[j].className = "selected";
                this.drawHeader(selectedDay.getDate());
                }
            }
        }
    };
    
    Calendar.prototype.clickDay = function(o) {
        var selected = document.getElementsByClassName("selected"),
            len = selected.length;
        if(len !== 0){
            selected[0].className = "";
        }
        o.className = "selected";
        selectedDay = new Date(year, month, o.innerHTML);
        this.drawHeader(o.innerHTML);
        this.setCookie('selected_day', 1);
        
    };





    
    Calendar.prototype.preMonth = function() {
        if(month < 1){ 
            month = 11;
            year = year - 1; 
        }else{
            month = month - 1;
        }
        this.drawHeader(1);
        this.drawDays();
    };
    
    Calendar.prototype.nextMonth = function() {
        if(month >= 11){
            month = 0;
            year =  year + 1; 
        }else{
            month = month + 1;
        }
        this.drawHeader(1);
        this.drawDays();
    };
    
    Calendar.prototype.getOptions = function() {
        if(this.options){
            var sets = this.options.split('-');
                setDate = new Date(sets[0], sets[1]-1, sets[2]);
                day = setDate.getDate();
                year = setDate.getFullYear();
                month = setDate.getMonth();
        }
    };
    
     Calendar.prototype.reset = function() {
         month = today.getMonth();
         year = today.getFullYear();
         day = today.getDate();
         this.options = undefined;
         this.drawDays();
     };
    
    Calendar.prototype.setCookie = function(name, expiredays){
        if(expiredays) {
            var date = new Date();
            date.setTime(date.getTime() + (expiredays*24*60*60*1000));
            var expires = "; expires=" +date.toGMTString();
        }else{
            var expires = "";
        }
        document.cookie = name + "=" + selectedDay + expires + "; path=/";
    };
    
    Calendar.prototype.getCookie = function(name) {
        if(document.cookie.length){
            var arrCookie  = document.cookie.split(';'),
                nameEQ = name + "=";
            for(var i = 0, cLen = arrCookie.length; i < cLen; i++) {
                var c = arrCookie[i];
                while (c.charAt(0)==' ') {
                    c = c.substring(1,c.length);
                    
                }
                if (c.indexOf(nameEQ) === 0) {
                    selectedDay =  new Date(c.substring(nameEQ.length, c.length));
                }
            }
        }
    };
    var calendar = new Calendar();
    
        
}, false);

})(jQuery);

// pop-up
const fetch =  require('node-fetch')
const form = document.querySelector('teacher-form');
//form.addEventListener("submit",async(event))
//const select = document.querySelector('#teacher-select');
//const submitButton = document.querySelector('#Check1');


form.addEventListener('submit', async(event) => {
    // Prevent the form from submitting
    event.preventDefault();
    // Get the form data
    //const FROM_DATE =document.getElementById("#options").value;
    const FROM_DATE = "2023-05-03";
    const TO_DATE =document.getElementById("#options").value;
    const T_CODE = document.getElementById('#teacher-select').value;
    const FROM_TIME = document.getElementById('#from-time').value;
    const TO_TIME = document.getElementById('#to-time').value;
    const DEPT = document.getElementById('#department').value;

    //const DATE = document.getElementById('#date').value;
    if (T_CODE.value == '' && T_CODE.value == 'a'){
        warn_popup();
    }
    else{
        const response = await fetch("/TAS/:usersid", {
            method: "GET",
            headers: {
                "Content-Type": "application/json; charset=UTF-8"
            },
            body: JSON.stringify({FROM_DATE,TO_DATE,FROM_TIME,TO_TIME,T_CODE}),
        });
        const data = await response.json();
        if(data.json[0]['available']===true){
           popup();
        }
        else{
            error_popup();
        }
       
    }
});
    

function popup(){
    //if condition for available is true then run this pop up
    {
    swal({
        title: "Yes!",
        text: "The Faculty is available!",
        icon: "success",
        button: "Ok!",
      });}
    }
function error_popup(){
      { //if condition false run this pop up
        swal({
            title: "Sorry!",
            text: "The Faculty is not available!",
            icon: "error",
            button: "Try Again!",
          });} 
    
}
function warn_popup(){
    { // if none of the value is selected for teachers
        swal({
            title: "Warning!",
            text: "Please first select the above details!",
            icon: "warning",
            button: "Try Again!",
          });} 
}

下面的代码在我用作后端节点 js 文件的 index.js 中。

const express = require('express')
const bodyParser = require('body-parser')
const { request } = require('http')
const nunjucks = require('nunjucks')
var multer = require('multer')
var upload = multer()
const app = express()
const db = require('./queries')
const helmet = require("helmet");
const morgan = require("morgan");
const cors = require("cors");
const port = 5500

app.use(bodyParser.json())
app.use(
    bodyParser.urlencoded({
        extended:true,
    })
)
app.get('/',(request,response)=> {
    response.json({info:'node.js,express'})
})
app.use(cors());
app.use(
  helmet.crossOriginResourcePolicy({
    policy: "cross-origin",
  })
);
app.use(morgan("common"));
// have res.render work with html files
app.set('view engine', 'html');
// when res.render works with html files, have it use nunjucks to do so
app.engine('html', nunjucks.render);
nunjucks.configure('../blah/views/index.html', { noCache: true });
app.use(upload.array()); 
app.use(express.static("../blah/"))
const router = express.Router();
app.use('/', router)
router.get('/TAS/usersid', function (req,res,next) {
    res.render('index', {});
})
app.get('/users', db.getUsers)
app.use(express.json());
app.get('/TAS/usersid', db.getUserById)
app.post('/usersin', db.createUser)
app.put('/usersup', db.updateUser)
app.delete('/usersdl', db.deleteUser)

app.listen(port,()=>{
    console.log(`App running on port ${port}.`)
})

rest 是对请求的输入数据起作用的查询。

const { request } = require('http') 
const fs = require('fs')
const weekday = ["SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY"]

const Pool = require('pg').Pool
const pool = new Pool({
    user: 'postgres',
    host:'localhost',
    database:'MiniProjS4',
    password:'Password',
    port:'5432'
})
 
const getUsers = (request, response) => {
  var {FROM_DATE,TO_DATE,FROM_TIME,TO_TIME,T_CODE} = (request.body)
    pool.query('SELECT * FROM CMPN_UPDATE_TABLE WHERE FROM_DATE=$1 AND TO_DATE=$2 AND FROM_TIME>=$3 AND TO_TIME<=$4 AND T_CODE=$5 ', [FROM_DATE,TO_DATE,FROM_TIME,TO_TIME,T_CODE], (error, results) => {
      if (error) {
        throw error
        }
        if (results.rows.length === 0) {
          getUserById(request, response);
        }
      response.status(200).json(results.rows)
    })
  }
  const getUserById = async (request, response) => {
    const { FROM_DATE, TO_DATE , FROM_TIME, TO_TIME, T_CODE,DEPT } = request.body;
    const d = new Date(FROM_DATE);
    const tablename = T_CODE + "_" + weekday[d.getDay()];
    
    const query = `SELECT AVAILABLE,LOC FROM ${tablename} WHERE FROM_TIME>=$1 AND TO_TIME<=$2`;
  
    pool.query(query, [FROM_TIME, TO_TIME], (error, results) => {
      if (error) {
        throw error;
      }
      response.status(200).json(results.rows);
    });  
    console.log(tablename);
  }
  
  
  
  const createUser = (request, response) => {
    const { FROM_DATE,TO_DATE,FROM_TIME,TO_TIME,T_CODE,AVAILABLE,REASON } = request.body
  
    pool.query('INSERT INTO CMPN_UPDATE_TABLE VALUES ($1,$2,$3,$4,$5,$6,$7)', [FROM_DATE,TO_DATE,FROM_TIME,TO_TIME,T_CODE,AVAILABLE,REASON], (error, results) => {
      if (error) {
        throw error
      }
      response.status(201).send(`User added with ID: $5`)
    })
  }
  
  const updateUser = (request, response) => {
    const id = parseInt(request.params.id)
    const { FROM_DATE,TO_DATE,FROM_TIME,TO_TIME,T_CODE,AVAILABLE,REASON} = request.body
  
    pool.query(
      'UPDATE CMPN_UPDATE_TABLE SET FROM_TIME = $3, TO_TIME = $4,AVAILABLE=$6,REASON=$7 WHERE T_CODE = $5 and FROM_DATE=$1  and TO_DATE=$2',
      [FROM_DATE,TO_DATE,FROM_TIME,TO_TIME,T_CODE,AVAILABLE,REASON],
      (error, results) => {
        if (error) {
          throw error
        }
        response.status(200).send(`User modified with ID: ${id}`)
      }
    )
  }
  
  const deleteUser = (request, response) => {
    const { from_date,to_date,t_code} = request.body
  
    pool.query('DELETE FROM cmpn_update_table WHERE d_code = $3  and from_date=$1  and to_date=$2', [from_date,to_date,t_code], (error, results) => {
      if (error) {
        throw error
      }
      response.status(200).send(`User deleted with ID: ${id}`)
    })
  }
  
  module.exports = {
    getUsers,
    getUserById,
    createUser,
    updateUser,
    deleteUser,
  }

  

代码不完整,因为我试图一次添加一个功能。

我尝试检查控制台和中间件,但登陆网页是作为响应而不是弹出功能发送的。

javascript node.js forms popup middleware
© www.soinside.com 2019 - 2024. All rights reserved.