簡體   English   中英

如何在瀏覽器的同一頁面中獲取HTML表單結果?

[英]How can I get the HTML form results in the same page of browser?

我正在用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";
?>
<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>

您必須在同一文件中組合PHP代碼和HTML代碼。
然后,您只需將表單操作設置為同一頁面即可。

<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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM