javascript - jQuery 和 PHP : Calculate the sum and send it back to client

标签 javascript php jquery ajax post

我有以下带有输入元素的 HTML 表单:

<form id="forma" name="forma" method="post">
   <div id="oblock">
      <div class="dtable">
        <div class="drow" id="drow1">
            <div class="dcell">
                <label for="aster">Aster:</label>
                <input type="text" id="aster" name="aster" value="0" stock="10" price="2.99" required>
            </div>
            <div class="dcell">
                <label for="daffodil">Daffodil:</label>
                <input type="text" id="daffodil" name="daffodil" value="0" stock="12" price="1.99" required >
            </div>
            <div class="dcell">
                <label for="rose">Rose:</label>
                <input type="text" id="rose" name="rose" value="0" stock="2" price="4.99" required>
            </div>
        </div>
    </div>
  </div>
  <div id="buttonDiv">
     <button type="submit">Place Order</button>
  </div>
</form>

我使用 jQuery serialize() 从表单收集数据并使用 $.post 发送到服务器端(在我的例子中为 test.php):

   $(function() {
        $("button").click(function(e) {
            var formData = $("form").serialize();
            $.post("test.php", formData, processServerResponse);
            e.preventDefault();
        });
    });
    function processServerResponse(data) {
         $("div.dcell").hide();
         $("#buttonDiv").append('<div>'+data.total+'</div>');
         $("#buttonDiv button").remove();
    }

如果我理解正确 - 使用 var formData = $("form").serialize(); 发送到服务器的数据将是一个如下所示的字符串:

"aster":"2"&"daffodil":"5"&"rose":"0"

1.如何在PHP中访问这些值?

2. 如果有大量输入元素,每个元素都有自己唯一的名称,我们如何迭代(并避免对每个元素单独使用 $_POST['input_name'] -> $_POST['aster']、$_POST['rose'] 等等...)并用 PHP 计算总和?

3.如何将计算出的总和发送回客户端(从从 PHP 到 jQuery/客户端)?

编辑2:

根据我在这里收到的一些答案,我尝试了以下方法:

<?php
    $sum = 0;
    foreach ($_POST as $name=>$value) {
        $sum += (int)$value;
    }
    $_POST['total'] = $sum;
    echo json_encode($_POST['total']);

我的客户端代码(jQuery):

function processServerResponse(data) {
        $("div.dcell").hide();
        $("#buttonDiv").append('<div>'+data+'</div>');
        $("#buttonDiv button").remove();
 }

它有效 - 它显示总和...

最佳答案

1 with $ _post ['varible-name'];

$asterPostVariable = $_POST['aster'];

2迭代$ _post数组

foreach ( $_POST as $key => $val )
{
  // Do calculation, your value from input element is in $val
  $sum += $val;
  // You could also check your $key if you don't want to sum all post variables
}

3 echo 为JSON DATA

echo json_encode( ['sum' => $calculatedSum] );

编辑

2迭代$ _post数组

foreach ( $_POST as $key => $val )
{
  // You could also check your $key if you don't want to sum all post variables. This solution is based on that your form elements that you want to calculate are named with the initial fl_
  if ( substr($key, 0, 3) == 'fl_' )
    $sum += $val;

}

关于javascript - jQuery 和 PHP : Calculate the sum and send it back to client,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34136814/

相关文章:

javascript - 在页面刷新时更改背景图像

php - Symfony 表单字段即使有错误也有效?

php - 为单页循环保留后过滤器

javascript - 如何添加动态 ID 并在运行时提取它们

javascript - 当 javascript 值插入到 .net 文本框时,document.getElementsByName(...)[0] 未定义

javascript - 在 jQuery 中切换 HTML 按钮时,时间戳不会更新为事件日期时间?

javascript - Cordova 无法检查循环内的 appAvailability。如何让循环等待 appAvailability.check 执行?

javascript - Angularjs 自定义表单控件范围重复

javascript - 查询指针数组 Mongoose Node.js

php - 没有正则表达式的句子大小写