gpt4 book ai didi

php - 将从 javascript 返回的值传递给 php

转载 作者:行者123 更新时间:2023-12-02 18:35:49 26 4
gpt4 key购买 nike

嗨,我在编程方面确实是新手,为了支持个人 promise ,我正在做一些 PHP 开发。

我编写了一个 JavaScript 来进行一些计算并返回答案。我想从我的 php 访问这个值并打印它。

以下是代码组件。

<?php include 'dbconnection.php'; ?>
<?php

$Kg=0.00;
$Rate=0.00; $MinusBags=0.00; $Amount = 0.00;
$KgIntoRate=0.00;
//$Amount = $KgIntoRate - $MinusBags;



//execute the SQL query and return records
$result = mysql_query("SELECT EmployeeName FROM employees");
$result2 = mysql_query("SELECT SRate FROM scraprates where SYear=YEAR(CURRENT_DATE()) AND SMonth=MONTHNAME(CURRENT_DATE())");
$temp1 = mysql_fetch_array($result2);
$Rate = $temp1['SRate'];
//$Rate=mysql_fetch_array($result2);


//fetch the data from the database
try{
while ($row = mysql_fetch_array($result)) {
echo "<tr><td>".$row{'EmployeeName'}."</td>";
echo "<td><input type='text' name='Kg' id='Kg' onChange='CalcKgIntoRate();'/></td>";
echo "<td>".$Rate."</td>";


// $KgIntoRate = $_GET['php_KgIntoRate'];
//echo "<td>".$_GET['php_KgIntoRate']."</td>";
echo "<td>".$KgIntoRate."</td>";

echo "<td><input type='text' name='MinusBags'/></td>";
echo "<td>".$Amount."</td></tr>";
}
}
catch(Exception $e)
{echo "error".$e;}
?>

<script type="text/javascript">
//$Kg= $('#Kg').val();
function CalcKgIntoRate(){
var Kg=document.getElementById('Kg').value;
var php_rate = "<?php echo $Rate; ?>";
var php_KgIntoRate = "<?php echo $KgIntoRate; ?>";
//document.write(Kg);
php_KgIntoRate=Kg*php_rate;
return php_KgIntoRate;
}
</script>

<?php
//function CalcKgIntoRate(){
//$KgIntoRate = $Kg * $Rate;
//echo "<td>".$KgIntoRate."</td>";
//}


//close the connection
mysql_close($dbhandle);
?>

我想做的是这个。名称和费率来自两个数据库表。我想根据输入的公斤数(在文本字段的更改事件上)计算 KgIntoRate 并在“公斤 * 速率”字段中显示该值。

我读到我需要使用 Ajax。但不知道该怎么做。感谢对代码的一些帮助。

最佳答案

我认为在您的示例中,您缺少的只是将值传递回输入字段。

   function CalcKgIntoRate(){
var Kg=document.getElementById('Kg').value;
var php_rate = "<?php echo $Rate; ?>";
var php_KgIntoRate = "<?php echo $KgIntoRate; ?>";
//document.write(Kg);
php_KgIntoRate=Kg*php_rate;
//return php_KgIntoRate;

// here! instead of returning the value, set it as the value of your Input
document.getElementById('Kg').value = php_KgIntoRate;}

或者你可以简单地在 php 中进行计算......

$result1 = $Rate * $KgIntoRate;
echo "<tr><td>".$row{'EmployeeName'}."</td>";
echo "<td><input type='text' name='Kg' id='Kg' value='".$result1."'/></td>";
echo "<td>".$Rate."</td>";

关于php - 将从 javascript 返回的值传递给 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17338321/

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