jquery - 使用node的Ajax post到sql不断增加发送的数据

标签 jquery mysql node.js ajax

我正在尝试学习如何在后端使用 node.js 以及在客户端使用 jQuery ajax 与数据库进行通信。

当用户第一次提交数据时,我已经有了基本的发布功能。然而,每当用户通过浏览器提交附加数据时,它都会作为多个重复行发送到 SQL 数据库表。此外,用户随后每次输入数据时,乘法次数都会增加。我不明白为什么会发生这种情况。

一些背景 我正在与世界各地的同事合作,分享一些使用小鼠体重的实验室数据。我的目标是让我的同事登录该网站,提交一些鼠标的基本数据,然后单击一个按钮。页面不会重新加载,并且先前的值不会重置,但用户可以手动清除先前的值以输入另一组数据。这是当新的数据集在 post 到 sql 上相乘时。

这是我的“工作”代码:

jQuery 监听点击事件

 // *********************************************
// Send Weights reference data to database
// *********************************************
$("#mouse_save").on("submit", function(e){
    //don't reload page
    e.preventDefault();

    //define ajax request data obj
    // Set Weights data object
    let mouseObj = {};

    mouseObj.ga = $('#mouse_age').val();
    mouseObj.weight = $('#mouse_wt').val();
    mouseObj.twin = $('#mouse_type option:selected').data('twin');

// get location data for submission
    $.ajax({
        url: "http://ip-api.com/json",
        type: 'GET',
        success: function(json)
        {
            mouseObj.country = json.countryCode;
            mouseObj.city = json.city;
            mouseObj.state = json.regionName;

        },
        error: function(err)
        {
            console.log("Geolocation Request failed, error= " + err);
        }
    }).done(function(response) {
        //ajax call to save new Weights object in the db when geoloc is done
        $.ajax({
            url: '/weight/add',
            type: 'POST',
            data: mouseObj,
            dataType: "json",
            cache: false
        });
        console.log("Weights data to DB", mouseObj);
    });
});

用于 POST 的 Node.js 后端

// post user's reference data to the database
router.post('/weight/add', (req, res) => {
    if (req.body){
        var data = req.body;
        var data_ga = req.body.ga;
        var data_weight = req.body.weight;
        var data_twin = req.body.twin;
        var data_country = req.body.country;
        var data_state = req.body.state;
        var data_city = req.body.city;
        console.log("Data added to weights DB:", data);

        // insert statment
        let sql = "INSERT INTO hemat.weightref (gestage, weight, twin, country, state, city) VALUES ('"+data_ga+"', '"+data_weight+"', '"+data_twin+"', '"+data_country+"', '"+data_state+"', '"+data_city+"')";

        // execute the insert statment
        connection.query(sql, function (err, results){
            if (err) {
                return console.error(err.message);
            } else {
                // get inserted id
                console.log('Row insert Id:' + results);
            }
        });
        res.end();
    } else {
        res.send("No data posted from client to send to DB");
    }
});

在数据库中 您可以看到第一次提交工作正常,但是当用户尝试提交另一组数据时,它会重复。如果他们尝试第三组,则会增加三倍,依此类推。

MySQL DB sample

编辑以在第二次单击按钮期间显示控制台日志 我在表单提交过程之前、期间和之内添加了一些控制台日志。我已附上下面的输出。我看到表单提交每次点击仅调用一次,但在第二次(以及后续点击) e.preventDefault (我用来防止页面重新加载)之后的代码块被多次调用。

2nd button click console log

如果您能帮助我停止后续单击按钮时的多次提交,我将不胜感激。

最佳答案

经过更多的 stackoverflow 挖掘,我偶然发现了这篇文章 (https://stackoverflow.com/a/18681588/1837608),它为我解决了问题。我将以下内容添加到我的客户端代码块中:

// *********************************************
// Send Weights reference data to database
// *********************************************
$("#mouse_save").on("submit", function(e){
    //don't reload page
    e.preventDefault();
    e.stopImmediatePropagation(); // added per solution referenced

    //define ajax request data obj
    // Set Weights data object
    let mouseObj = {};

    mouseObj.ga = $('#mouse_age').val();
    mouseObj.weight = $('#mouse_wt').val();
    mouseObj.twin = $('#mouse_type option:selected').data('twin');

// get location data for submission
    $.ajax({
        url: "http://ip-api.com/json",
        type: 'GET',
        success: function(json)
        {
            mouseObj.country = json.countryCode;
            mouseObj.city = json.city;
            mouseObj.state = json.regionName;

        },
        error: function(err)
        {
            console.log("Geolocation Request failed, error= " + err);
        }
    }).done(function(response) {
        //ajax call to save new Weights object in the db when geoloc is done
        $.ajax({
            url: '/weight/add',
            type: 'POST',
            data: mouseObj,
            dataType: "json",
            cache: false
        });
        console.log("Weights data to DB", mouseObj);
    });
return false; // added per solution referenced
});

关于jquery - 使用node的Ajax post到sql不断增加发送的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56403421/

相关文章:

jQuery 不适用于同一类别的第二项

PHP MySQL 区分大小写

javascript - 从 ReactJS 应用程序调用 CMD 命令行

jquery - 2 列主体,可变宽度,100% 高度,固定页眉和页脚

jquery - ASP.NET MVC 有拼写检查器吗?

mysql - 从matlab动态调用mysql过程

mysql - 在mysql json中按值删除数组元素

node.js - NodeJS | Mongoose 不更新数据库中的值

node.js - 如何使用 Material-UI 创建 onSubmit

javascript - 使用 sortable.js 时禁用 bootstrap wysihtml5