我怎样才能捕捉到JavaScript的PHP的会话变量不刷新页面?变量、捉到、页面、PHP

2023-09-10 18:09:30 作者:蝴蝶少女。

我有一个的index.php ,在那里我做在session_start()等。登录,我发Ajax请求 receiver.php ,在这里我设置会话变量等,并得到一个Ajax响应了。

I have an index.php, where I do session_start() etc. For login, I send an ajax request to receiver.php, where I set the session variables etc and get an ajax response back.

现在,我可以完美地捕捉到PHP的会话变量的的只有当我刷新的的的index.php 页有以下code:

Now, I can perfectly capture the php session variables only when I refresh the index.php page that has the following code:

jsSessionUserId = <?php     
    if (isset($_SESSION['userId'])) { //LoggedIn:
        echo json_encode($_SESSION['userId']); 
    } else { //  Not logged in.
        // some code here
    }
?>;

我真正想要的是,当我收到一个成功的Ajax响应(因此没有必要刷新的index.php 页)。这是行不通的。我怀疑是PHP不相当的javascript函数内的工作。感谢您的任何帮助。

What I really want is to put this in a function and then call this function when I receive a successful ajax response (and thus not have the need to refresh the index.php page). It is not working. I suspect that the php doesn't quite work inside of a javascript function. Grateful for any help.

推荐答案

这是坏主意混为一谈。像PHP和JavaScript。你最简单的解决方案,现在 - 一旦收到成功登录响应覆盖您的JavaScript变量

It is bad idea to mix things up. Like php and javascript. Easiest solution for you right now - overwrite your javascript variables once successful login response is received.

$.post("receiver.php", formData, function(response){ // login callback
  if(response.UserId){ // return user id if login is successful
    jsSessionUserId = response.UserId; // overwrite old variable
  }
}, "json");