【问题标题】:Passing input value to another page using $_SESSION使用 $_SESSION 将输入值传递到另一个页面
【发布时间】:2016-07-18 08:59:58
【问题描述】:

我尝试在用户单击提交按钮后使用 Session 方法将用户的输入值传递到另一个页面。

我的页面有一个带有一个按钮的表单,称为“添加文本框”。此按钮允许用户自己添加文本框。

这是我当前的代码

$(document).ready(function() {

  var counter = 2;

  $("#addButton").click(function() {

    if (counter > 10) {
      alert("Only 10 textboxes allow");
      return false;
    }

    var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);

    newTextBoxDiv.after().html('<label>Textbox #' + counter + ' : </label>' + '<input type="text" name="textbox' + counter + '" id="textbox' + counter + '" value="" >');

    newTextBoxDiv.appendTo("#TextBoxesGroup");


    counter++;
  });

  $("#removeButton").click(function() {
    if (counter == 2) {
      alert("System required at least one.");
      return false;
    }

    counter--;

    $("#TextBoxDiv" + counter).remove();

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form action="<?php $_PHP_SELF ?>" method="post">
  <div id='TextBoxesGroup'>
    <div id="TextBoxDiv1">
      <label>Textbox #1 :</label>
      <input type='textbox' id='textbox1' name="textbox1">
    </div>
  </div>
  <input type='button' value='Add Button' id='addButton'>
  <input type='button' value='Remove Button' id='removeButton'>
  <br/>
  <input type="submit" name="submit" id="submit">
</form>

这是我在 php 中将值分配给会话的代码

<?php
        if(isset($_POST['submit'])) {
            for($i=1; $i<=10; $i++)
            {
                if(isset($_POST['textbox'.$i]))
                {
                    $obj = $_POST['textbox'.$i];
                    echo $obj,'<br>';
                    $_SESSION['textbox'.$i] = $obj;
                }
            }
            header("Location:../brightan-system/result.php");
       }
    ?>

这是我尝试从第二页获取值的方式

<?php
    for($i=1; $i<=10; $i++)
    {
        echo "<strong>".$i."</strong> ".$_SESSION['textbox'.$i]."<br>";//Use the session variables
    }
    session_destroy();
?>

其实我可以在第二页得到结果,但问题是如果用户只添加4个文本框,那么第二页就会出现Undefined index的错误。这是因为 for 循环在第二页产生了 10 个会话变量。

在这种情况下,是否有另一种方法来获取会话变量而不是使用 for 循环?

【问题讨论】:

  • 您可以简单地使用&lt;input type="text" name="textbox[]',而不是使用计数器设置输入名称。在 php 方面,您可以使用 count($post['textbox']) 来获取文本框的计数并在循环中使用此计数。

标签: javascript php html session input


【解决方案1】:

您应该首先检查是否设置了 ith 文本框。添加条件以在打印前检查。

<?php
for($i=1; $i<=10; $i++)
{
  if(isset($_SESSION['textbox'.$i])){
    echo "<strong>".$i."</strong> ".$_SESSION['textbox'.$i]."<br>";//Use the session variables
  }
}
session_destroy();

?>

【讨论】:

    猜你喜欢
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    相关资源
    最近更新 更多