我有两个php页面。在first.php页面中,用户可以选择订单,并且div中会填充这些内容,这没问题。还有一个确认按钮来确认这些列表。当用户单击此按钮时,应打开second.php页面,并且div的内容应显示在该页面上。这是我为first.phpdiv和confirm按钮编写的html代码。
<form method="post">
<div class="col-md-5" id="orderList">
<h3 align="centre">Order List</h3>
</div>
</form>
<form role="form" method="post" action="second.php">
<div id="firstConfirmButton">
<button type="submit" name="firstConfirmButton" id="firstConfirmButton" class="btn btn-primary btn-lg">Confirm</button>
</div>
</form>
这是将内容发布到second.php的javascript代码。第一个警报工作正常,但第二个警报不正常。
$("#firstConfirmButton").click(function() {
var content = $('#orderList').html();
alert(content);
$.post("second.php", { html: content})
.done(function(data) {
alert(data);
$('#confirmForm').empty().append(data);
});
});
Second.php页面有confirFormdiv,我想显示其中的内容。
<div id="confirmForm"> </div>
问题出在哪里?
您的按钮是submit
按钮,因此如果您不取消默认事件,表单也将以常规方式提交。
您需要捕获事件并取消它:
$("#firstConfirmButton").click(function(e) {
var content = $('#orderList').html();
e.preventDefault();
// the rest of your code
或者在现代版本的jQuery中:
$("#firstConfirmButton").on('click', function(e) {
var content = $('#orderList').html();
e.preventDefault();
// the rest of your code
您使用POST方法将表单提交到页面second.php,因此可以使用以下php代码从第二个页面检索数据:
var_dump($_POST);
因此,基本上,数据存储在$_POST
数组中。
关于你的第二个问题。如果您首先需要从Javascript中获取值,则需要避免提交默认表单。你可以这样做:
$("#firstConfirmButton").click(function(e) {
var data = $('#orderList').html();
e.preventDefault();
//...
}
这将避免您的提交按钮在不添加所需POST数据的情况下提交表单。