我的“帖子”表格没有发布

时间:2013-04-08 05:11:59

标签: php ajax

尝试使用SESSION将数据从一个页面发送到另一个页面时遇到问题。 在第1页中,我有一个表格:

<form id="myForm"  name="myForm" action="" method="post">

<input name="item_1">......</input> // an input for a number
<input name="comment1">......</input> // an input for text

</form>

为避免刷新,我使用

function submitOnclick()
{
    $.post("thisPage.php", $("#myForm").serialize());
    redirectToAnotherPage();
}

然后我尝试使用SESSION存储数据

function redirectToAnotherPage(){
    <?php $_SESSION['item_1']=$_POST['item_1'] ?>;
    <?php $_SESSION['comment1']=$_POST['comment1'] ?>;
    location.href='anotherPage.php';
}

但是$ POST结果为空,我尝试用数字1替换$ _POST ['item_1']并且它确实将数字存储到item_1,所以我认为这是因为$ _POST ['item_1']有一些问题,我不知道为什么我不能在没有提交/刷新的情况下在一个页面中获取表单数据,

任何帮助将不胜感激,谢谢!

2 个答案:

答案 0 :(得分:0)

我认为您不能在javascript函数中设置类似的PHP会话变量。 PHP与javascript是分开的,因为PHP是服务器端,当页面首次预处理时,这些值将被读取并分配。

无论是否调用javascript函数都没有变化。

即使没有AJAX&lt;只需一个简单的PHP表单即可。请参阅以下内容:

<form id="myForm"  name="myForm" action="anotherPage.php" method="post">

    <input name="item1">......</input>
    <input name="comment1">......</input>

</form>

要使用javascript提交,只需在您的函数中使用类似的内容:

function submitForm() {
    document.myform.submit();
}

答案 1 :(得分:0)

问题是您输入的name与您的$_POST索引

不一致

您的输入:<input name="item1">

您的帖子索引:$_POST['item_1']

并且它在Js中使用PHP函数的方法也不正确,这个:

function redirectToAnotherPage(){
  <?php $_SESSION['item_1']=$_POST['item_1'] ?>;
  <?php $_SESSION['comment1']=$_POST['comment1'] ?>;
  location.href='anotherPage.php';
}

您需要直接在$_SESSION(ajax post url)中设置thisPage.php

编辑:

不要使用serialize(),而是这样:

function submitOnclick()
 {
   $.post(
     "thisPage.php",
     {item_1 : $('input[name="item_1"]').val(),
      comment1 : $('input[name="comment1"]').val()
      }
   );
   redirectToAnotherPage();
 }
祝你好运!!!

相关问题