在一个页面中有两个表单并设置会话

时间:2015-10-29 17:37:17

标签: php forms session

我有两个文件和两个表单:

文件1:

<form name="name1" action="form2.php" method="post">
     <input <? $_session['define'] = 'value1' ?> type="submit" ...>
</form>
<form name="name2" action="form2.php" method="post">
     <input <? $_session['define'] = 'value2' ?> type="submit" ...>
</form>

如您所见,我有两个表单和两个不同的提交按钮但是当我按下每个表单时,第二个值(最后一个)设置为$ _session [&#39;定义&#39;],并且在第二个表单中我总是拥有&#39; value2&#39;。

1 个答案:

答案 0 :(得分:0)

您必须将数据发布到PHP:

<form name="name1" action="form2.php" method="post">
     <input name='v1' value='1' type="submit" />
</form>
<form name="name2" action="form2.php" method="post">
     <input name='v2' value='2' type="submit" />
</form>

在form2.php中:

<?php
session_start();
$_SESSION['value1'] = isset($_POST['v1'])?$_POST['v1']:0;
$_SESSION['value2'] = isset($_POST['v2'])?$_POST['v2']:0;
?>

就个人而言,我会将其作为一个表单并使用JQuery / AJAX来发布值。

<form id="selectForm" name="name1" action="form2.php" method="post">
     <input id="v1" name='v1' value='1' type="submit" />
     <input id="v2" name='v2' value='2' type="submit" />
</form>
<script>
// Requires JQuery
$("#selectForm input[id^='v']").click(function(e){
    e.preventDefault();
    $.post(form2.php, { $(this).attr("name"): $(this).attr("value") }, function(){ alert("Selection Saved.) });
});
</script>