Javascript 不从数据库向上添加变量

Javascript not adding variables from database up

本文关键字:添加 变量 数据库 Javascript      更新时间:2023-09-26

大家好,所以基本上我正在尝试在我构建的营养标签中添加数据。所以标签本身有脂肪、碳水化合物、蛋白质等一切。现在我已经建立了一个数据库:

ingName: ...
fat: ...
Carbs: ....
etc etc 

所以现在我只是想让它对脂肪起作用。一旦我这样做了,我就可以轻松地完成其他工作。我可以轻松地搜索数据库。当用户按下添加按钮时,它将在搜索框下方添加成分,然后更改脂肪的含量。但是,如果用户添加花药记录,则脂肪含量不会加在一起。

例如,我有香蕉有 4 种脂肪,苹果有 1 种脂肪。我先加苹果,脂肪含量变为1脂肪。当我添加香蕉时,它应该变成 5 脂肪,但它实际上会变成 4。因此,记录没有正确加起来。

Js:

        else{ 
            var searchedValue = $('#search_term').val(); 
            var temp2 = 0; 
            $.post( 'build.php', { 'search_term':searchedValue, 'current_fat':temp2 }, function(data) { 
            $('.result').html( data ); 
            }); 
            temp = $("#fat").text(); 
            temp = parseInt(temp); 
            current_fat += temp2; 
            current_fat += temp; 
            console.log(temp + " " + temp2 + " " + current_fat); 
            $("#fat").text(current_fat);

导致问题的部分在 else 循环中,我似乎无法弄清楚如何解决它,

如果您需要 php 文件,我可以为您提供它,但它似乎在 js 文件的 else 循环中,但我似乎无法弄清楚如何解决它。大约一个星期以来,我一直被困在这个精神问题上:)

无论如何感谢您的帮助 x

试试这个:

$('#addButton').on('click', function( event ) {
   //your other stuff
   var searchedValue = $('#search_term').val(); 
   //remove this : var temp2 = 0; 
   //add this:
   temp = $("#fat").text(); 
   temp = parseInt(temp);
   //change your post reg to:
   $.post( 'build.php', { 'search_term':searchedValue, 'current_fat':temp }, function(data) { 
       $('.result').html( data ); 
    }); 
   //rest of your code...