EJS模板中的setInterval()不起作用 [英] setInterval() in EJS template does not work

查看:45
本文介绍了EJS模板中的setInterval()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在家庭作业项目中遇到问题.我正在尝试一个项目,其中比特币的价格将每秒更新一次.现在,API请求运行正常,我可以看到EJS模板渲染的数据,但是我无法每秒更新一次价格.谁能检查我的代码,看看我的代码有什么问题吗?有关参考,请访问www.preev.com.它显示了我希望如何更新价格.并检查下面我的代码.

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. Can anyone check my code and see if anything is wrong in my code? For reference please check www.preev.com. It shows how I want the price to be updated. And also check below my code.

我试图在app.js文件中调用API请求,并将其呈现在一个名为results.ejs的EJS模板中.

I have tried to call the API request in app.js file and rendered it in an EJS template called results.ejs.

app.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

results.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>

推荐答案

初始答案

您的setInterval可以正常工作,只是在您的函数内部,数据永不更改.

Initial answer

Your setInterval works fine, it's just that inside your function the data never changes.

要解决此问题,您必须引用一个变量(其内容会更改),而不是对函数中的值进行硬编码.

To fix it you have to reference a variable (of which the content changes), rather than hardcoding the value in your function.

例如,您正在使用EJS,这是一种模板语言.模板语言根据您的变量(每页加载一次)解析输出.

For example you are using EJS, which is a templating language. A templating language parses output based on your variables (once per page load).

您的模板行

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

解析为

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

然后您的时间间隔将每隔 500 毫秒用该值更新 #showPrice innerHTML .

And your interval then updates the innerHTML of #showPrice with that value, every 500 ms.

您可能要做的是从客户端(浏览器)发出请求,然后将其响应存储到变量中,例如 latestResult ,然后对函数进行编码以引用该变量,例如所以:

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:

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

示例实现

这意味着您的快速应用程序(app.js)将在没有数据的情况下呈现结果:

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)

请注意,我在这里将 request 更改为 fetch ,因为我不确定您的客户端代码是否具有babel,因此我使用了浏览器的本机获取API .

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.

这篇关于EJS模板中的setInterval()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆