gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:38:25 25 4
gpt4 key购买 nike

我有以下带有输入元素的 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. 如何将计算出的总和发送回客户端(f从 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 使用 $_POST['变量名'];

$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 将其作为 json 数据回显

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com