【发布时间】:2025-11-22 11:50:01
【问题描述】:
我在使用 angular.js 和 php 的 $http 请求 errorCallback 函数中有一个问题。这里我有一个登录页面,当我输入错误的用户名/密码时,值总是返回到 successCallback 函数。我在下面解释我的代码。
loginController.js:
var loginAdmin=angular.module('Channabasavashwara');
loginAdmin.controller('loginController',function($scope,$http,$location){
$scope.user_name = '';
$scope.user_pass = '';
$scope.user_type= '';
$scope.user_login=function(){
if($scope.user_name==''){
alert('user name filed should not keep blank');
}else if($scope.user_pass==''){
alert('password filed should not keep blank');
}else if($scope.user_type==''){
alert('Please select your user type');
}else{
var userData={'user_name':$scope.user_name,'user_pass':$scope.user_pass};
if($scope.user_type=='admin'){
$http({
method: 'POST',
url: "php/Login/login.php",
data: userData,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
console.log('response',response);
alert(response.data['msg']);
$location.path('dashboard');
},function errorCallback(response) {
alert(response.data['msg']);
});
}
if($scope.user_type=='hod'){
$http({
method: 'POST',
url: "php/Login/hodLogin.php",
data:userdata,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
alert(response.data['msg']);
$location.path('dashboard');
},function errorCallback(response) {
alert(response.data['msg']);
});
}
}
}
});
login.php:
<?php header("HTTP/1.0 401 Unauthorized");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$user_name=$request->user_name;
$user_pass=$request->user_pass;
$connect = mysql_connect("localhost", "root", "****");
mysql_select_db('go_fasto', $connect);
$selquery = "SELECT * FROM db_Admin_Master WHERE user_name='".$user_name."' and password='".$user_pass."'";
$selres = mysql_query($selquery);
if(mysql_num_rows($selres ) > 0){
$result=mysql_fetch_array($selres);
$result['msg'] = 'Login successfull...';
}else{
$result['msg'] = 'You entered wrong username/password';
}
echo json_encode($result);
?>
这里我的问题是假设用户输入了错误的用户名和密码消息(i.e-You entered wrong username/password)总是返回successCallback函数,应该返回errorCallback函数。这里我的要求是成功消息将返回seccessCallback函数并且错误消息将返回到 errorCallback 函数。请帮助我。
【问题讨论】:
-
请尝试将带有状态码的
HTTP标头设置为错误可能是401<?php header("HTTP/1.0 401 Unauthorized"); ?> -
通过回显消息,您的回调不会知道是否发生了错误。所以你需要设置一个标题。
-
@maniteja:你能编辑你的答案吗?
-
@maniteja :对于这两种情况,我都按照您的要求执行了 errorCallBack 函数。
-
请分享更新后的代码。
标签: javascript php angularjs http callback