Pass received server data to Client Javascript

Asked

Viewed 76 times

0

Suppose I have the following page made in HTML that shows the name {{name}} and data {{ date}} both information came from the server:

<h1>Seu nome é {{name}} </h1>
<h1> A data de hoje é {{date}}</h1>

However, how would I do if hypothetically I want to pass the amount contained in {{date}} for the following function (script) added to the submitted html (?):

<script>

function mostradata (date) {
    alert(date)
  }

</script> 

In short: I want my displayed function to receive the parameter {{date}} that came from the server.

  • 1

    I suggest you take a look at the Jade template engine. And you already have an answer here as well. https://answall.com/questions/198999/passar-variável-para-página-html-com-nodejs

  • pq does not create a variable with the value of {{date}} and then use?

1 answer

1


this is quite simple actually, you have to be aware that it is possible to take values of your HTML with JS, just use Document.getElementById or Document.getElementByClass among others.

Let’s say you chose to use getElementByid

You must declare id, so we can do the following:

<h1 id="myId"> A data de hoje é {{date}}</h1>

And now with JS you take this element:

<script>

function mostradata () {

    return document.getElementById("myId").textContent

  }

console.log(mostradata())


</script> 

With this script every time you update the page it will call this function and pick up content from the tag text that has the myId id and in this case display in the console.

Now if the case is to take only the date is just adapt this code, instead of you passing the id to H1 is just create a child TAG inside H1, it may be for example a span, then:

<h1> A data de hoje é <span id="myId">{{date}}</span></h1>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.