简体   繁体   English

在Node.js Express网站上使用Jquery Ajax POST

[英]Using Jquery Ajax POST on Node.js Express site

Everything is working fine with the forms post requests I've done so far, but when I try to make an Ajax call I'm not able to deal with it on the server. 到目前为止,我完成的表单发布请求一切正常,但是当我尝试进行Ajax调用时,无法在服务器上处理它。 Although it returns the 'succeed' param, I'm not able to save the information on the database nor make any acions with it on the server. 尽管它返回了“成功”参数,但我无法将信息保存在数据库中,也无法在服务器上进行任何处理。

page.jade: page.jade:

script
        (function () {

            $('ul').find('a').on("click", function () {
                var option = $(this).data('res');
                $('article').animate({ 'margin-left': -600 });
                console.log(option + ' ' + #{idn});

                var envio = {resultado: option, idupdate: #{idn}};

                $.ajax({
                        url: '/',
                        type: "post",
                        data: JSON.stringify(envio),
                        contentType: 'application/json',
                        success: function(data) {
                            console.log('success');
                        }
                    });
            });
        })();

server.js server.js

app.post('/', function (req, res) {

    var Resultado = req.body.resultado;
    var idUpdate = req.body.idupdate;

    if (Resultado == "yes") {
        connection.query('UPDATE questions SET yes=yes+1 WHERE id=' + idUpdate + ');');
    } else {
        connection.query('UPDATE questions SET no=no+1 WHERE id=' + idUpdate + ');');
    }
});

I tried to find any similar situation around, but the information on this particular case is scarce. 我试图找到任何类似的情况,但是有关此特定案例的信息很少。 Thanks!!! 谢谢!!!

Looks like both querys are malformed, 看起来两个查询的格式都不正确,

connection.query('UPDATE questions SET yes=yes+1 WHERE id=' + idUpdate + ');');
                                                           (here)   ----^   
connection.query('UPDATE questions SET no=no+1 WHERE id=' + idUpdate + ');');
                                                     (and here)   ----^ 

Then, remove + ');' 然后,删除+ ');' part and it should work. 部分,它应该工作。

Like: 喜欢:

connection.query('UPDATE questions SET yes=yes+1 WHERE id=' + idUpdate);

Aditionaly you need to end the request, calling res.end() 另外,您需要结束请求,调用res.end()

final code: 最终代码:

app.post('/', function (req, res) {

    var Resultado = req.body.resultado;
    var idUpdate = req.body.idupdate;

    if (Resultado == "yes") {
        connection.query('UPDATE questions SET yes=yes+1 WHERE id=' + idUpdate);
    } else {
        connection.query('UPDATE questions SET no=no+1 WHERE id=' + idUpdate);
    }
    res.end(); // must be called.
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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