如何使用PHP将具有特定ID的元素从一个页面发布到另一个页面?

时间:2017-05-07 12:08:14

标签: javascript php html

firstpage.html:

<body>
<?php
$text = $_POST['text'];
?>
<p style = "color:red; " id = "getext"><?php echo $text; ?></p>
</body>

secondpage.php:

<body>
<?php
$text = $_POST['text'];
?>
<p style = "color:red; " id = "getext">i want $text var to appear here</p>
</body>

我想提前感谢id为“gettext”的p元素从第一页到第二页的文本节点

1 个答案:

答案 0 :(得分:2)

我们无法直接发布文本节点。所以我们必须为此改变逻辑。

<form action = "secondpage.php" method = "POST" onsubmit="return false" name="form1">
<p id="txtNode">textnode</p>
<input type=button onclick="submitForm()" value="Submit">
<input type=hidden id="text" name="text">
</form>

此处我们通过设置 onsubmit =&#34;返回false&#34; 来禁用表单的默认提交操作,然后我们定义了 onclick =&#34; submitForm()& #34; 用于提交表单的按钮。在 submitForm()函数中,我们将文本节点复制到隐藏字段并提交表单,如下所示:

function submitForm(){
var txtNode = document.getElementById("txtNode").innerHTML;
document.getElementById("text").value=txtNode;
document.forms["form1"].submit();
}

然后在 secondpage.php 上,您将能够获得该值:

<?php
$text = isset($_POST['text'])?$_POST['text']:"";
?>
<p style = "color:red; " id = "getext"><?php echo $text; ?></p>