简体   繁体   English

从console.log获取值到html

[英]Getting value from a console.log to html

The function I have written works fine and the value correctly writes to my terminal onSubmit, however I'm struggling to piece together why this code isn't updating my html. 我写的函数工作正常,值正确写入我的终端onSubmit,但是我很难拼凑为什么这段代码没有更新我的html。

router.post('/index', function(req, res, next) {

  // ...Get form values, do calculations to get toCost value.

      console.log('$' + toCost);

      $(document).ready(function() {
        var output = document.getElementById('cost');
        output.innerHTML = toCost;
      });

  res.location('/');
  res.redirect('/');
})

I receive the following error and jquery is loading fine. 我收到以下错误,jquery正在加载正常。

$ is not defined

Admittedly this is an over-engineered node/express app. 不可否认,这是一个过度设计的节点/快递应用程序。 The code snippet lives wrapped in a route file, inside a post request. 代码片段包含在邮件请求中的路由文件中。

How do I get my value onto the html? 如何将我的价值放到html上?

Jade layout 玉的布局

extends layout

block content
  form(...)
  div#cost

The normal way to do this would be as follows: 通常的方法如下:

router.post('/index', function(req, res) {   <<< 'next' removed (only needed if using middleware)

  // ...Get form values, do calculations to get toCost value.

  console.log('$' + toCost);

  res.render('indexTemplate', {cost: toCost}); <<< pass toCost through to jade as 'cost'
});

Then in your jade file for the indexTemplate you can reference the 'cost' variable passed in like this: 然后在indexTemplate的jade文件中,您可以像这样引用传入的'cost'变量:

indexTemplate.jade: indexTemplate.jade:

extends layout

block content
  form(...)
  div#cost #{cost} <<< adds the cost variable to page

Then the value of toCost will appear in the resulting page. 然后,toCost的值将出现在结果页面中。

No jQuery is required on the server side. 服务器端不需要jQuery。

jQuery is made for DOM manipulations and there's no DOM on a server. jQuery是为DOM操作而制作的,服务器上没有DOM。 Try using 'jsdom'. 尝试使用'jsdom'。 jQuery is made for client side scripting, not for server-side client manipulations. jQuery是为客户端脚本编写的,而不是服务器端客户端操作。

It seems that you're trying to make changes on client-side from your backend. 您似乎正在尝试从后端在客户端进行更改。 It doesn't work that way. 它不起作用。

You could create a variable on backend for storing calculation result. 您可以在后端创建一个变量来存储计算结果。 And get this value by get query from client-side 并通过从客户端get查询来获取此值

You're tring to reach DOM (that is on client side) from NodeJS on a server side. 你想从服务器端的NodeJS到达DOM(在客户端)。 It doesn't work that way. 它不起作用。

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

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