通过javascript发布数据时可以设置会话变量吗? [英] Can i set session variables when posting data via javascript?

查看:62
本文介绍了通过javascript发布数据时可以设置会话变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的PHP登录身份验证脚本,现在我想覆盖从表单到auth脚本的数据发布,以便它通过ajax进行操作.

I created a simple PHP login authentication script, now i want to override the posting of data from the form to the auth script so that it does it via ajax.

我这样做是为了使PHP以{"success":[1 OR 0],"error";"ANY ERROR MESSAGE RELATED TO SUCCESS = 0"}格式返回JSON数据,这非常有效,当我尝试使用登录表单时,当我序列化表单并将其发布到auth脚本时,它将返回success:1.正确的用户名+密码,它返回success:0以及登录错误的原因,在原始方法中,表单已发布到auth脚本,然后在成功登录后将auth脚本重定向到受保护的页面,我将其替换为javascript成功接收到登录后更改窗口位置的方法,唯一的问题是似乎没有通过此方法将会话变量设置为从发布到auth脚本.

I made it so that the PHP returns JSON data in the format {"success":[1 OR 0],"error";"ANY ERROR MESSAGE RELATED TO SUCCESS = 0"}, this works perfectly and when i try and use the login form it returns success:1 when i serialize the form and post it to the auth script with a correct username+password and it returns success:0 and the reason why with an incorrect login, on the original method where the form posted to the auth script, then the auth script redirected to a protected page after succesful login i have replaced this with the javascript changing the window location after it recieves a succesful login, only problem being is that is seems the session variables havent been set from posting to the auth script via this method.

有没有一种方法可以使会话变量固定住而无需直接定向到页面?

Is there a way i can make the session variables stick without actually having to direct to the page?

推荐答案

创建&使用JavaScript访问会话变量

使用JavaScript创建会话变量

<?php session_start(); ?>
<html>
<head>
<script type='text/javascript'>
    function setSession(variable, value) {
        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "setSession.php?variable=" + variable + "&value=" + value, true);
        xmlhttp.send();
    }
</script>
</head>
<body>
<?php
    if(isset($_SESSION['login']) && $_SESSION['login'] == "true")
      echo "Session Active. <a href=\"javascript:setSession('login', 'false')\"><input type='submit' value='De-Activate'></a>";
    else
      echo "Session Inactive. <a href=\"javascript:setSession('login', 'true')\"><input type='submit' value='Activate'></a>";
      echo "<a href=\"index.php\"><input type='submit' value='Re-Load Page'></a>";
?>
</body>
</html>

为其分配值

<?php
    session_start();
    if(isset($_REQUEST['variable']) && isset($_REQUEST['value']))
    {
        $variable = $_REQUEST['variable'];
        $value = $_REQUEST['value'];
        $_SESSION[$variable] = $value;
    }
?>

这篇关于通过javascript发布数据时可以设置会话变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆