从nodejs函数更新p元素

时间:2017-09-26 20:58:35

标签: javascript jquery html node.js express

我需要从输入表单向nodejs服务器发送一个值,该服务器触发使用此值进行计算,并且需要使用客户端计算结果更新p元素。

如何做到这一点?

这就是我所拥有的:

//服务器端:

    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");
                },
            });              
        });

2 个答案:

答案 0 :(得分:0)

好的,所以你不提供大量的数据,但这听起来就像将结果的响应发送到Node Web服务中的客户端进行计算并将结果附加到P元素< / p>

答案 1 :(得分:0)

处理ajax调用的服务器代码应该输出一个json响应,该响应将包含<p>的内容。它不应该重新呈现整个索引页面。我没有做很多node.js所以我会留下让你弄明白的。

ajax success函数应该接受响应作​​为参数,然后对该响应进行操作。

假设服务器对此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");
        },
    });