简体   繁体   中英

401 Unauthorized Issue

I am using the jQuery.get() method

$.get('login.php', function(d, textStatus, jqXHR){
    //alert(jqXHR.status)
    var status = jqXHR.status; 
    if((status==200)||(status==202)){
        window.location.href = 'dashboard.html';
    }else if(status==401){
        alert('Error in login details')
    }else{
        alert('Unknown Error')
    }
});

It is working fine. When 200 & 202 , It will rediredt to dashboard page. But Other than 200 & 202, It pass the error in console but doesn't show alert.

You need to add in some event handlers for the fail state, which will handle 4xx and 5xx errors. The success state only handles HTTP codes which indicate a successful request. From http://api.jquery.com/jQuery.get

var jqxhr = $.get( "example.php", function(data, status) {
  alert( "success - " + status );
})
.done(function(data, status) {
  alert( "second success - " + status );
})
.fail(function(data, status) {
  alert( "error - " + status );
})
.always(function(data, status) {
  alert( "finished - " + status );
});

This is because the callback function you have defined is only called when a successful request completes. If the response is anything other than a 200, the request is considered to have errored. To do what you require, you could use the $.ajax() method:

$.ajax({
    url: 'login.php', 
    success: function() {
        window.location.assign('dashboard.html');
    }, 
    error: function(xhr) {
        if (xhr.status == 401) {
            alert('Error in login details')
        } else {
            alert('Unknown Error')
        }
   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM