简体   繁体   English

EJS 模板中的 setInterval() 不起作用

[英]setInterval() in EJS template does not work

I'm currently stuck with a problem in a homework project.我目前在家庭作业项目中遇到问题。 I'm trying to make a project where the price of bitcoin will update every second.我正在尝试制作一个比特币价格每秒都会更新的项目。 Now the API request is working fine and I can see the data render from an EJS template but I can't make the price update every second.现在 API 请求工作正常,我可以看到从 EJS 模板呈现的数据,但我无法每秒更新价格。 Can anyone check my code and see if anything is wrong in my code?任何人都可以检查我的代码,看看我的代码有什么问题吗? For reference please check www.preev.com.如需参考,请查看 www.preev.com。 It shows how I want the price to be updated.它显示了我希望如何更新价格。 And also check below my code.还要检查下面我的代码。

I have tried to call the API request in app.js file and rendered it in an EJS template called results.ejs.我尝试在 app.js 文件中调用 API 请求,并将其呈现在名为 results.ejs 的 EJS 模板中。

app.js应用程序.js

var express = require("express");
var app = express();
var request = require("request");


app.set("view engine", "ejs");


app.get("/", function(req, res) {
    request("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_market_cap=true&include_24hr_vol=true&include_24hr_change=true&include_last_updated_at=true", function(error, response, body) {
        if(!error && response.statusCode == 200) {
            var data = JSON.parse(body);
            res.render("result", {data: data});
        }
    });
});




app.listen(3000, function(){
    console.log("server has started");
});


results.ejs结果.ejs

<h1>
    Bitcoin Latest
</h1>



Price: $ <span id="showPrice"></span> 
<br>
MarketCap: $<%= data["bitcoin"]["usd_market_cap"] %>
<br>
24h Volume: $<%= data["bitcoin"]["usd_24h_vol"] %>
<br>
24h Change: <%= data["bitcoin"]["usd_24h_change"] %>%


<script>
    function updatePrice(){
        document.getElementById("showPrice").innerHTML= <%= data["bitcoin"]["usd"] %>;
    };

    setInterval(updatePrice, 500);
</script>

Initial answer初步答复

Your setInterval works fine, it's just that inside your function the data never changes.您的 setInterval 工作正常,只是在您的函数内部,数据永远不会改变。

To fix it you have to reference a variable (of which the content changes), rather than hardcoding the value in your function.要修复它,您必须引用一个变量(其内容会发生变化),而不是在函数中对值进行硬编码。

Extra explanation额外说明

For example you are using EJS, which is a templating language .例如,您正在使用 EJS,它是一种模板语言 A templating language parses output based on your variables (once per page load).模板语言根据您的变量解析输出(每个页面加载一次)。

Your template line你的模板行

document.getElementById("showPrice").innerHTML= <%= data["bitcoin"]["usd"] %>;

parses into解析为

document.getElementById("showPrice").innerHTML= 9624.46;

And your interval then updates the innerHTML of #showPrice with that value, every 500 ms.然后您的时间间隔每500毫秒用该值更新#showPriceinnerHTML

What you probably mean to do is make the request from the client (the browser), then store its response into a variable, say latestResult , and then code your function to reference that variable, like so:您可能想要做的是从客户端(浏览器)发出请求,然后将其响应存储到一个变量中,例如latestResult ,然后编写您的函数以引用该变量,如下所示:

document.getElementById("showPrice").innerHTML= latestResult;

Example implementation示例实现

This means that your express application (app.js) will render result without data:这意味着您的快速应用程序 (app.js) 将在没有数据的情况下呈现result

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

And the request part will be in your template:请求部分将在您的模板中:

function updateLatestPrice() {
  fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_market_cap=true&include_24hr_vol=true&include_24hr_change=true&include_last_updated_at=true').then((result) => {
    const latestResult = result.bitcoin.usd

    document.getElementById("showPrice").innerHTML = latestResult || 'failed'
  })
}

setInterval(updateLatestPrice, 3000)

Note that I changed request into fetch here because I couldn't be sure whether your client code has babel, so I went with the browser's native Fetch API .请注意,我在这里将request更改为fetch因为我无法确定您的客户端代码是否有 babel,所以我使用了浏览器的原生Fetch API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM