JQuery数量的单元格,用PHP计算总和

时间:2014-04-24 09:08:36

标签: php jquery

我正在尝试发送每个单元格的数字,并在php中计算它们的总和。然后在文本输入中显示结果但它没有用。我怎么能这样做?

这是我的PHP代码:

<?php

    if(isset($_POST['keyup'])){
    $sum1 = $_POST['sum1'];
    $sum2 = $_POST['sum2'];
    $sum3 = $_POST['sum3'];

    $resultado = $sum1+ $sum2 + $sum3;

     echo "Resultado: " .'<input type="text" name="resultado" value="'.$resultado.'">';

 }


?>

FULL FIDDLE CODE

提前感谢

1 个答案:

答案 0 :(得分:1)

我快速查看了您的完整代码,似乎缺少表单标记。 您需要在表单标记之间体现代码。这将运行一个脚本。

<form action="yourphpfile" method="post"></form>

如果您不想加载新页面,则需要使用更复杂的Ajax。 有关表格的更多信息,请点击此处。 http://www.w3schools.com/php/php_forms.asp

编辑动作脚本将在单击某种提交输入按钮时运行。

第二次编辑。 我查看了一些旧项目,看看我是如何刷新一个带有ajax的页面,如下所示。

//This function will need to be called on a button click for example
function login(){
    var sum1 = document.getElementById("sum1");
    var sum2 = document.getElementById("sum2");
    var sum3 = document.getElementById("sum3"); 
    //Do some extra refining here if needed. Depends on how the data is obtained.
    sum1 = sum1.value;
    sum2 = sum2.value;
    sum3 = sum3.value;
    //Calls the functions below
    ajax(sum1, sum2, sum3);
}

//Javascript call this function on a button click 
//or create an extra function that calls this and loads the sums from the page.
function Ajax(sum1, sum2, sum3){
    var xml;
    xml = setXML(xml);
    xml.onreadystatechange=function(){
        if (xml.readyState==4 && xml.status==200){
            document.getElementById(DIV THAT WILL NEED TO BE UDATED HERE ).innerHTML=xml.responseText;
        }
    };
    xml.open("POST", URLTOYOURSCRIPT.php ,true);
    xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xml.send("sum1="+sum1+"&sum2="+sum2+"&sum3="+sum3+);
}
function setXML(xml){
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
    xml = new XMLHttpRequest();
    return xml;
    }
    else{// code for IE6, IE5
    xml = new ActiveXObject("Microsoft.XMLHTTP");
    return xml;
    }
}

然后您的PHP脚本将需要以下内容。

//Obtains the sums from the post data send by ajax.
$sum1 = $_POST["sum1"];
$sum2 = $_POST["sum2"];
$sum3 = $_POST["sum3"];
//Perform some extra checks here like isnumeric() to see if they are actual numbers etc.
if(is_numeric($sum1) && is_numeric($sum2) && is_numeric($sum3){
    //Calculates the sum and echoes it on your existing page.
    $totalsum = $sum1+$sum2+$sum3;
    echo $totalsum;
}else{
    echo "you did not insert numbers"
}