Update part of HTML page without reloading the page using expressJs nodeJs Handlebars

家住魔仙堡 提交于 2019-12-07 12:58:05

问题


I have the following express app which just renders the ecommerce.hbs page.On that page i have one section suppose To Do List section and it shows four to five tasks with checkbox.when I change the checkbox the attached script run and send the id of changed checkbox to routing file where i have get the id and run loop to change value from true to false and false to true.I have console the value and it returns correct value after click on checkbox but i stuck to send data back to the ecommerce.hbs page for To Do List section.How can i send data back to ecommerce.hbs page without reloading the page.

ecommerce.js(routing)

router.get('/ecommerce', function(req, res, next) {
  res.render('ecommerce', { 
        layout:'main',
      data: data
    });
});

router.post('/ecommerce', (req, res) => {
   var id = req.body.id;
   //console.log(req.body.id)
   res.json({
      success: true
   });
   for (var i=0; i<data.todo.length; i++){
      if(data.todo[i]['id'] == id){
         data.todo[i]['completed'] = !data.todo[i]['completed'];
         //console.log(data.todo[i]['completed']);
      }
   }
});  

ecommerce.hbs file

 {{#toDoList data.todo}}
      {{> widgets/toDoList}}
 {{/toDoList}}

toDoList section

<input type="checkbox" name="task" id="{{id}}" autocomplete="off" checked="" onchange="return onToDochange(this)">

On Change script

function onToDochange(event) {
   //console.log(event.id);
   $.ajax({
      url: "/ecommerce",
      method: 'POST',
      headers: {
         'Accept': 'application/json',
      },
      data: {
         id : event.id
      },
      body: JSON.stringify({"id": event.id})
   })
   .done(function( data ) {
      console.log( "Sample of data:", data );
    });
  };

Thankyou!!

来源:https://stackoverflow.com/questions/52441069/update-part-of-html-page-without-reloading-the-page-using-expressjs-nodejs-handl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!