问题描述
限时送ChatGPT账号..我目前在家庭作业项目中遇到问题.我正在尝试制作一个比特币价格每秒都会更新的项目.现在 API 请求工作正常,我可以看到从 EJS 模板呈现的数据,但我无法每秒更新价格.任何人都可以检查我的代码,看看我的代码有什么问题吗?如需参考,请查看 www.preev.它显示了我希望如何更新价格.还要检查下面我的代码.
我尝试在 app.js 文件中调用 API 请求,并在名为 results.ejs 的 EJS 模板中呈现它.
app.js
var express = require("express");var app = express();var request = require("请求");app.set("查看引擎", "ejs");app.get("/", function(req, res) {request("https://api.coingecko/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,响应,正文){if(!error && response.statusCode == 200) {var data = JSON.parse(body);res.render("result", {data: data});}});});app.listen(3000, 函数(){console.log("服务器已经启动");});
结果.ejs
比特币最新
价格:$<span id="showPrice"></span><br>市值:$<%= 数据[比特币"][usd_market_cap"] %><br>24 小时交易量:$<%= data["bitcoin"]["usd_24h_vol"] %><br>24 小时变化:<%= data["bitcoin"]["usd_24h_change"] %>%<脚本>函数更新价格(){document.getElementById("showPrice").innerHTML= <%= data["bitcoin"]["usd"] %>;};设置间隔(更新价格,500);</script>
解决方案 初始答案
您的 setInterval 工作正常,只是在您的函数内部,数据永远不会改变.
要修复它,您必须引用一个变量(其内容会发生变化),而不是在函数中硬编码该值.
额外说明
例如,您正在使用 EJS,它是一种模板语言.模板语言根据您的变量解析输出(每个页面加载一次).
您的模板行
document.getElementById("showPrice").innerHTML= <%= data["bitcoin"]["usd"] %>;
解析为
document.getElementById("showPrice").innerHTML= 9624.46;
然后您的时间间隔会使用该值更新 #showPrice
的 innerHTML
,每 500
毫秒.
您可能想要做的是从客户端(浏览器)发出请求,然后将其响应存储到一个变量中,例如 latestResult
,然后编写您的函数以引用该变量,例如所以:
document.getElementById("showPrice").innerHTML= latestResult;
示例实现
这意味着您的 express 应用程序 (app.js) 将在没有数据的情况下呈现 result
:
app.get('/', function(req, res) {res.render('结果');});
请求部分将在您的模板中:
function updateLatestPrice() {fetch('https://api.coingecko/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((结果) => {const latestResult = result.bitcoin.usddocument.getElementById("showPrice").innerHTML = latestResult ||'失败的'})}设置间隔(更新最新价格,3000)
<块引用>
注意我这里把request
改成了fetch
,因为我不能确定你的客户端代码是否有babel,所以我用浏览器原生的Fetch API.
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. 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
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/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
<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.
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. 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.
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;
Example implementation
This means that your express application (app.js) will render result
without data:
app.get('/', function(req, res) {
res.render('result');
});
And the request part will be in your template:
function updateLatestPrice() {
fetch('https://api.coingecko/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
intofetch
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屋!
更多推荐
[db:关键词]
发布评论