我在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";
?>
答案 0 :(得分: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>
答案 1 :(得分:2)
您必须将PHP代码和HTML代码组合在同一个文件中 然后,您只需将表单操作设置为同一页面。
答案 2 :(得分: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.