3

我正在用 PHP 和 HTML 输入一个简单的代码。如何在浏览器的同一页面而不是另一个窗口选项卡或页面中显示结果?

以下是简单的 HTML 公式代码:

将两个数字相加并显示在同一页面上

<html>
<head>
    <title> Sum of two numbers </title>
<body>

    <form action="sum.php" method="POST">
    First Number:  <input type="Text" Name="Num1"><br>
    Second Number: <input type="Text" Name="Num2"><p>
    <input type="Submit" value="Calculate">
    </form>

</body>
</html>

文件sum.php如下。

<?php
// add First and Second Numbers
$sum = $_POST["Num1"] + $_POST["Num2"];
// their sum is diplayed as
echo "The sum of  First Number (".$_POST["Num1"].") and
Second Number  (".$_POST["Num2"].") is $sum";
?>
4

3 回答 3

4
<html>
<head>
    <title> Sum of two numbers </title>
<body>

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
    First Number:  <input type="Text" Name="Num1"><br>
    Second Number: <input type="Text" Name="Num2"><p>
    <input type="Submit" value="Calculate">
    </form>

<?php
if (count($_POST) > 0 && isset($_POST["Num1"]) && isset($_POST["Num2"])){
    // add First and Second Numbers
    $sum = $_POST["Num1"] + $_POST["Num2"];
    // their sum is diplayed as
    echo "The sum of  First Number (".$_POST["Num1"].") and
    Second Number  (".$_POST["Num2"].") is $sum";
}
?>
</body>
</html>
于 2012-11-28T23:23:38.153 回答
2

您必须将 PHP 代码和 HTML 代码组合在同一个文件中。
然后,您只需将表单操作设置为同一页面。

于 2012-11-28T23:19:39.547 回答
1
<html>
<head>
    <title> Sum of two numbers </title>
<body>
<?php 
if($_POST["Num1"]=='' And $_POST["Num2"]==''){
?>      
    <form action="sum.php" method="POST">
    First Number:  <input type="Text" Name="Num1"><br>
    Second Number: <input type="Text" Name="Num2"><p>
    <input type="Submit" value="Calculate">
    </form>
<?php }else{
// add First and Second Numbers
$sum = $_POST["Num1"] + $_POST["Num2"];
// their sum is diplayed as
echo "The sum of  First Number (".$_POST["Num1"].") and
Second Number  (".$_POST["Num2"].") is $sum";
} ?>
</body>
</html>

and sum.php file is as follows.
于 2012-11-28T23:24:06.990 回答