将变量值从php传递给angular javascript

时间:2015-05-13 07:11:25

标签: javascript php angularjs

在我的用户控制器中,lodgin函数检查我的数据库中是否有数据 并且执行一个条件,无论它是真还是假,我的问题是我怎样才能传递它的值 在我的PHP中的$ valid变量并在我的userlogin javascript中传递给它?对不起,我的英语不好。

PHP:

public function loginAction() {
  if (!isset($_POST['data']))
    jsonOut($response - > status = 'failed');

  $user_data = json_decode($_POST['data']);
  $response = new stdClass();

  $this - > users_model_instance - > student_username = $user_data - > username;
  $this - > users_model_instance - > student_password = $user_data - > password;

  $valid = $this - > users_model_instance - > Login();

  if ($valid) {

    jsonOut($response - > status = 'success');
  } else {

    jsonOut($response - > status = 'failed');
  }
}

JavaScript的:

(function() {
  var app = angular.module("userlogin", []);

  app.controller("UserLoginController", ["$location", "ngDialog", "$scope", "httpRequest",
    function($location, ngDialog, $scope, httpRequest) {

      $scope.students = {};
      $scope.newStudents = {};
      $scope.startTest = false;
      $scope.students;

      $scope.submitLogin = function() {
        var request = {};
        request.url = '/account/users/login';
        request.method = 'POST';
        request.data = angular.toJson($scope.students);

        var onSuccess = function(data, status, headers, config, statusText) {

          if (status == 'true') {
            alert('success!');
            $location.url('/examdirection/');
          } else if (status == 'failed') {
            alert('failed!');
          }
        };
        httpRequest(request, $scope.response, onSuccess);
      };
    }
  ]);
})();

1 个答案:

答案 0 :(得分:1)

考虑查看$http以发出异步请求。 这是一个例子:

Angular:

$scope.submitLogin = function() {
    //You don't need to serialize the data into json
    $http.post('/account/user/login', $scope.students).success(function(data){
        //We enter here when the http response status code is a success 2XX
        alert('success!');
        $location.url('/examdirection/');
    }).error(function(){
        //We enter here when the http response status code is an error 4XX, 5XX
        alert('failed!');
    });
};

Php(您需要在框架中找到设置$响应响应代码的方法):

if($valid){
    //It should look like $response->setStatusCode(200)
    //http_response_code is for pure php http manipulation
    http_response_code(200);
}else{
    //Choose the best http code in your case
    http_response_code(400);
}

希望它会帮助你。