从PHP文件中获取$ _session变量并在AJAX中使用

时间:2011-10-26 22:46:03

标签: php ajax session-variables

在使用脚本语言方面我很新,所以我很难理解这些概念。

基本上我有这个表格

<form method="post" action="/list/process.php">
 <input type="email" name="address" value ="Email" />
 <input type="hidden" name="lists[]" value="122" />
 <input type="submit" name="submit" value="Join" />
</form>

process.php验证电子邮件地址的正确语法,如果成功检查数据库的地址是否已存在(“取消订阅”)或不存在(“订阅”)

我将这个PHP片段包含在表单页面

<div id="result">
<?php
   if ($_SESSION['result'] == ("fail"))
    {
    echo "<p>Please enter a valid email address!</p>";
    }

   if ($_SESSION['result'] == ("success") && $_SESSION['action'] == ("subscribe"))
    {
    echo "<p>Thankyou for joining, you will shortly receive an email at $_SESSION[address]' with a link to your free download.</p><p>Note: if you do not receive an email, please check your junk folder and mark the message as safe.</p>";
    }

   if ($_SESSION['result'] == ("success") && $_SESSION['action'] == ("unsubscribe"))
    {
    echo "<p>You will shortly receive an email with a link to unsubscribe from the mailing list.</p>";
    }
?>
</div>

不确定我的PHP语法是否符合临时(我是新手),但它确实有效。当然div#results显示为“请输入有效的电子邮件地址!”当你最初加载页面时,因为$ _SESSION ['result']返回“失败”。当我提交表格时,所有其他可能性都有效。

现在我将如何在AJAX中复制此PHP代码段?我想这将涉及使用AJAX将表单发布到process.php,获取三个会话变量,然后以上述方式处理它们(但在JavaScript中)以在最初隐藏的div中显示三个消息之一(#结果)以弹出/冒泡的方式。

问题是如何?我没有使用AJAX的经验,这似乎是我能达到预期结果的唯一方法。

谢谢你的帮助。

亚当

1 个答案:

答案 0 :(得分:1)

我认为在这种情况下可能不需要使用会话。

这就是我要做的事情:

  • 首次加载表单时,请使用javascript隐藏div#result
  • 当有人通过process.php提交表单时,处理表单并返回一个包含错误消息列表的JSON数组和一个表示提交是否成功的变量。
  • AJAX方应接收响应,查看成功变量,如果为false,请将这些消息插入div#result并取消隐藏div。