AngularJS ngRoute和PHP $ _SESSION变量 [英] AngularJS ngRoute and PHP $_SESSION variables

查看:91
本文介绍了AngularJS ngRoute和PHP $ _SESSION变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3页:

  1. index.php
  2. login.php
  3. display.php

index.php

使用ngRoute模块设置AngularJS来浏览我的页面.

index.php

Sets up AngularJS using the ngRoute module to navigate my pages.

默认加载并设置PHP $ _SESSION变量.

Loaded by default and sets PHP $_SESSION variables.

回显$ _SESSION的内容.

Echos the contents of $_SESSION.

我使用ngRoute的链接设置从login.php导航到display.php.

I navigate to display.php from login.php using a link setup with ngRoute.

display.php不会显示$ _SESSION变量,无论我导航多少次.仅当我手动导航到该页面(例如刷新页面或在浏览器中输入地址)时,它才会显示它们.

display.php does not show $_SESSION variables no matter how many times I navigate to and from it. It will only display them if I manually navigate to the page such as refreshing the page or entering the address in the browser.

我知道php代码已执行,因为我可以在屏幕上回显其他内容,因为它只是无法访问$ _SESSION变量.

I know the php code is executed because I can echo other things to the screen it just doesn't access the $_SESSION variables.

这是为什么?

推荐答案

我想我可能会看到您的问题在哪里.您尝试在单页angularJS HTML模板中访问php会​​话,对吗?像:

I think i might see where your problem is. You try to access php session in your single page angularJS HTML templates am i right? like:

<div ng-repeat="n in <?php $_SESSION['someSessionArray'] ?>">

这不是它的工作方式.您的$ _SESSION在模板中将永远不可用. 您可以做的是使用ajax请求进行登录身份验证,并让该请求为您提供会话ID. 然后在其他ajax请求中启动会话时使用该会话ID(如上所述).

That is not how it works. Your $_SESSION will never be available in your templates. What you can do, is use an ajax request for your login authentication and have that request give you a session id. Then use that session id when starting your session in further ajax requests (as already mentioned).

然后,当您想在php会话中存储内容时,通过ajax请求和php服务访问数据.

Then, when you want to store something to the php session, access the data via ajax request and php service.

一个非常,非常,非常简单的示例: 在getFromSession.php里面

a VERY, VERY, VERY, simple Example: inside getFromSession.php

session_start($_GET['session_id']);
$key = $_GET['key']
echo json_encode($_SESSION[$key]);

在storeToSession.php内部

inside storeToSession.php

session_start($_GET['session_id']);
$key = $_GET['key'];
$value = $_GET['value'];
$_SESSION[$key] = $value;

在您的login.php内

inside your login.php

$user = yourAuthMechanism($_GET['username'],$_GET['password']);
if($user) {
  session_start();
  echo json_decode(array('status' => 'success','sid' => session_id()));
}
else { ... error handling

在您需要访问会话数据的任意位置:

inside anywhere in your angular where you need to access session data:

$promise = $http.get('pathtoyourphp/getFromSession.php?key=foo');
$http.set('pathtoyourphp/getFromSession.php?key=bar&value=4');
// now use promise to acces the data you got from your service

这篇关于AngularJS ngRoute和PHP $ _SESSION变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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