嗨,我非常喜欢编程和做一些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);
?>
我想做的就是这个。名称和速率来自两个数据库表。我想根据输入的Kg(在文本字段的更改事件中)计算KgIntoRate,并在Kg * Rate字段中显示该值。
我读到我需要使用Ajax。但不知道该怎么做。感谢代码的一些帮助。
答案 0 :(得分:1)
如果您的计算是在javascript中处理的话,那么您可以在没有ajax的情况下执行此操作:
检查它是否对您有所帮助。
e.g。 更改在PHP代码中:
$i = 0; // define outside the loop
echo "<td><input type='text' name='Kg' id='Kg".$i."' onChange='CalcKgIntoRate(".$i.");'/></td>";
echo "<td id='rate".$i."'>".$KgIntoRate."</td>";
echo "<td id='kg_into_rate".$i."'>".$Amount."</td></tr>";
$i++;
JS代码:
function CalcKgIntoRate(i) {
var kg = document.getElementById('Kg'+i).value;
var rate = document.getElementById('rate'+i).innerHTML;
var kg_into_rate = document.getElementById('kg_into_rate'+i);
// here is your calculation login
// suppose you store the calculation in an another variable
var calVal = parseFloat(kg*eval(rate));
kg_into_rate.innerHTML = calVal;
}
答案 1 :(得分:1)
我认为在您的示例中,您遗漏的只是将值传递回Input字段。
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>";