【问题标题】:Posting Div Content in Php在 PHP 中发布 div 内容
【发布时间】:2014-10-31 21:11:16
【问题描述】:

我有两个 php 页面。在 first.php 页面中,用户选择订单,一个 div 填充了这个内容,没问题。并且有一个确认按钮来确认这些列表。当用户单击此按钮时,应该会打开 second.php 页面,并且应该在该页面上显示 div 的内容。这是我的 first.php div 和确认按钮的 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 页面有confirForm div,我想在其中显示内容。

    <div id="confirmForm"> </div>

问题出在哪里?

【问题讨论】:

  • 第二页将包含所有已发布的项目,位于恰当命名的 $_POST 数组中。
  • 当我尝试使用 $_POST 获取数据时,我看到了 array(1) { ["firstConfirmButton"]=> string(0) "" }
  • @user3235456 看我的回答;)

标签: javascript php jquery html


【解决方案1】:

你的按钮是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

【讨论】:

  • 谢谢,我将此添加到我的代码中。现在我可以看到.done之后的警报但是这次我无法打开second.php?
  • @user3235456 您应该使用console.log() 而不是alert(),这将为您提供更多信息。在控制台中,您还会看到错误消息,例如脚本的路径是否错误。如需更多帮助,您需要准确说明问题所在。
  • 控制台没有错误,当我在 .done [Log] array(1) { (script.js, line 112) ["html"] 中看到 console.log(data) => string(240) "

    Sipariş Listesi

    1 Adet Tall Fat Caramel Frappuccino Sipariş listesinden çıkarmak için tıklayın!

    " }
  • @user3235456 如果您进入.done() 处理程序,则您的php 脚本已成功执行。如果结果不是您想要的,那么问题出在您的 php 脚本中。
  • 其实我在console.log中看到了我想要的。但我需要在 second.php 中看到这一点。你认为我的 second.php 或 first.php html 部分有什么错误?
【解决方案2】:

您使用 POST 方法将表单提交到页面 second.php,因此可以使用以下 PHP 代码从第二个页面检索数据:

var_dump($_POST);

所以基本上,数据存储在$_POST 数组中。

关于你的第二个问题。如果您首先需要从 Javascript 中获取值,则需要避免提交默认表单。你可以这样做:

$("#firstConfirmButton").click(function(e) {
  var data = $('#orderList').html();
  e.preventDefault();

  //...
}

这将避免您的提交按钮在提交表单时未添加所需的 POST 数据。

【讨论】:

  • 我看到 array(1) { ["firstConfirmButton"]=> string(0) "" } 当我这样做时
  • 是的,这是您在表单中设置的firstConfirmButton按钮的值,属性为:name="firstConfirmButton"
  • 但是我想要id=orderList的div的值,怎么办?
  • 您的 javascript 正在提交表单本身,您需要阻止默认提交。我会更新我的答案。
  • 我做到了,但更新后我无法打开 second.php
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-28
  • 2014-01-18
  • 2012-07-09
  • 2016-01-09
  • 1970-01-01
  • 2014-06-06
相关资源
最近更新 更多