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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度