我如何将数据从ejs文件获取到外部javascript文件

时间:2019-05-16 21:18:57

标签: node.js express

我正在尝试创建一个表单,在该表单中向用户询问一定的时间,然后使用计时器倒计时呈现该页面的时间。我遇到的问题是,我可以使用EJS和呈现将homePage.ejs中指定的用户的时间变量转换为timerPage.ejs,但是我不知道如何将时间变量转换为timer.js(即timerPage)。 ejs用于显示计时器。

homePage.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

    <form action="/" method="POST">
        <label>Set Timer To: </label>
        <input name = "timerTime" type="text">
        <button type ="submit">Start</button>
    </form> 
</body>
</html>

app.js

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

app.set("view engine", "ejs"); 
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

app.get('/', function(req,res){
    res.render('homePage');
});

app.post('/', function(req,res){
    let time = req.body.timerTime;
    res.render('timerPage', {timerTime: time});
});


app.listen(3000, function(){
    console.log('server listening on port 3000!');
});

timerPage.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body >

    <div id="countdown">00:00</div>
    <div id="pause">Pause</div>
    <div id="resume">Resume</div>

</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src= "timer.js"></script>
</html>

timer.js

var CountDown = (function ($) {
// Length ms 
var TimeOut = 10000;
// Interval ms
var TimeGap = 1000;

var CurrentTime = (new Date()).getTime();
var EndTime = ( new Date() ).getTime() + TimeOut;

var GuiTimer = $('#countdown');
var GuiPause = $('#pause');
var GuiResume = $('#resume').hide();

var Running = true;

var UpdateTimer = function() {
    // Run till timeout
    if( CurrentTime + TimeGap < EndTime ) {
        setTimeout( UpdateTimer, TimeGap );
    }
    // Countdown if running
    if( Running ) {
        CurrentTime += TimeGap;
        if( CurrentTime >= EndTime ) {
            GuiTimer.css('color','red');
        }
    }
    // Update Gui
    var Time = new Date();
    Time.setTime( EndTime - CurrentTime );
    var Minutes = Time.getMinutes();
    var Seconds = Time.getSeconds();

    GuiTimer.html( 
        (Minutes < 10 ? '0' : '') + Minutes 
        + ':' 
        + (Seconds < 10 ? '0' : '') + Seconds );
};

var Pause = function() {
    Running = false;
    GuiPause.hide();
    GuiResume.show();
};

var Resume = function() {
    Running = true;
    GuiPause.show();
    GuiResume.hide();
};

var Start = function( Timeout ) {
    TimeOut = Timeout;
    CurrentTime = ( new Date() ).getTime();
    EndTime = ( new Date() ).getTime() + TimeOut;
    UpdateTimer();
};

return {
    Pause: Pause,
    Resume: Resume,
    Start: Start
};
})(jQuery);

jQuery('#pause').on('click',CountDown.Pause);
jQuery('#resume').on('click',CountDown.Resume);

// ms
CountDown.Start(120000);

0 个答案:

没有答案