简体   繁体   中英

Node.js and existing Div in HTML Page

I was reading solution to a problem I am facing in node.js and found a question that is already answered: Node.js send HTML as response to client

But I was looking for something else.

I have a form on the server and a div as part of client HTML. User clicks on the button to send a request to server. Server, in turn, checks the request and send response back to client browser. What I would like to do here is to append the response data in an existing HTML div on the client browser.

For example, I would like to fill data in existing HTML DIV as part of below code:

app.post('/process_post', urlencodedParser, function (req, res) {  
   // Prepare output in JSON format  
  response = {  
      first_name:req.body.first_name,  
      last_name:req.body.last_name  
      // HERE I would like to use HTML coding to insert data to existing HTML DIV.
  };  
  console.log(response);  
  res.end(JSON.stringify(response));  
})  

Thank you.

Your server should send the data required back to the client as a JSON object in the response, and then you can use JavaScript on the client to do what you want through the following steps:

  • Use something like document.getElementById to select your div, such as const elem = document.getElementById("your-id");
  • Update the contents of the div with innerHTML elem.innerHTML = new data;

EDIT: You can create a function that will send an async Ajax request to the server when the button is clicked, then use promise handling to update the div content. For example, using axios library for Ajax as that's what I'm familiar with:

const launchAjax = (formData) => {
    axios.post("/process_post", formData)
        .then(responseData => {
            const elem = document.getElementById("your-id");
            // Assuming required data is called info in JSON
            elem.innerHTML = responseData.info;
        });
const button = document.getElementById("button-id");
button.addEventListener("click", launchAjax);

Or with the fetch API natively supported by browsers:

const launchAjax = (formData) => {
    fetch("/process_post", {
        method: "POST",
        body: JSON.stringify(formData)
    })
        .then(response => response.json())
        .then(responseJSON => {
            const elem = document.getElementById("your-id");
            // Assuming required data is called info in JSON
            elem.innerHTML = responseData.info;
        });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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