2017-09-26 61 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"); 
     }, 
    });