dongmieqiao3152 2014-08-15 06:31
浏览 56
已采纳

使用angularjs和php登录[关闭]

Im going to try to build an login system with angularjs and php. However, I don't know how Im going to handle the sessions and the redirection when the user has successfully logged in?

Should I start a session in the backend with PHP, and then return it to back to angular? Should I use window.location.href when Im going to redirect the user?

  • 写回答

1条回答 默认 最新

  • douxing1353 2014-08-15 06:38
    关注

    You can use Php session and return it to Angular service. Then you can share your user information with service to other controllers.

    I recommend you to use ngRoute and shared service which contains user information. This method is very fast and secure.

    I just edit my answer and made a quick example for you.

    var doc = angular.module('doc',
    [
        'ngRoute'
    ]);
    
    doc.service('link', function () {//Creating my service
        this.user = false;//Here is my user object. I am changing these datas in the login section.
    
    });
    
    doc.config(function($routeProvider, $locationProvider) {
        $routeProvider
         .when('/homepage', {
             templateUrl: 'view/homepage.html',
             controller: 'homePage',
         })
        .when('/login', {
            templateUrl: 'view/login.html',
            controller: 'login',
        })
        $locationProvider.html5Mode(true);
    });
    
    doc.controller("login", function ($scope, $timeout, link, $location) { //As you see I sent 'link' as a parameter. So I can easily use my service and the user data.
        $scope.username = "";
        $scope.password = "";
        $scope.login = function () {
            $.get("/login.php", {username:$scope.username,password:$scope.password},function(data){
                if(data){
                    link.user = JSON.parse(data); // I am parsing my json data and save to link.user
                    $location.path("/homapage");
                }
            });
        }
    });
    
    
    doc.controller("homePage", function ($scope, $timeout, link, $location) { //As you see I sent 'link' as a parameter. So I can easily use my service and the user data.
        if(link.user){
            console.log(link.user); // I can access my user!
        }else{
            $location.path("/login");
        }
    });
    

    As you see my service contains my user datas which I initialized at the login page. Now I am using them in my controllers easily.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据