2017-09-26 76 views
0

我需要从一个输入表格发送一个值到的NodeJS服务器,其触发的计算以该值和需要更新与在客户端的计算的结果的p元素的p元件。更新从的NodeJS功能

这怎么办?

这是我有:

//服务器端:

app.post('/calculate/:id', function(req, res){ 
    var title = 'Tax Calculation'; 
    var tax= taxcalculation(req.params.id); 
    res.render('index', { 
     title: title, 
     tax: tax, 
    }); 
}); 

//客户端:

var income= document.getElementById("income"); 
     var tax = document.getElementById("tax") 
     $(income).on('change', function() { 
      console.log("changed"); 
      $.ajax({ 
       type: 'POST', 
       url: '/calculate/'+income.value, 
       success: function() { 
        $('#tax').html('<%= tax %>'); 
       }, 
       error: function() { // if error occured 
        alert("Error occured, please try again"); 
       }, 
      });    
     }); 

回答

0

好了,你不给大量的数据,不过这听起来发送的结果到客户端在你的节点的网络服务,做了计算,并将结果追加到P元素的响应简单

+0

我能够与页面的刷新,更新p元素。我怎么能做到这一点,而不刷新页面? – rlacle

+0

当你可以做这样的事情'的document.getElementById(“yourParagraph”)的innerHTML = response.data响应;' –

0

您的服务器代码来处理Ajax调用应输出JSON响应将包含为<p>内容。它不应该重新呈现整个索引页面。我不会做很多node.js,所以我会留下让你弄清楚。

阿贾克斯成功函数应该接受作为参数的响应,并对该响应工作。

假设服务器响应此Ajax请求的格式是{"tax": 15.99}的:

$.ajax({ 
     type: 'POST', 
     url: '/calculate/'+income.value, 
     success: function(response) { 
      if (response.tax || response.tax === 0) { 
      $('#tax').html(response.tax); 
      } 
     }, 
     error: function() { // if error occured 
      alert("Error occured, please try again"); 
     }, 
    });