Use basic authentication with jQuery and Ajax

前端 未结 10 1077
野的像风
野的像风 2020-11-21 06:11

I am trying to create a basic authentication through the browser, but I can\'t really get there.

If this script won\'t be here the browser authentication will take o

10条回答
  •  梦谈多话
    2020-11-21 07:04

    Use the beforeSend callback to add a HTTP header with the authentication information like so:

    var username = $("input#username").val();
    var password = $("input#password").val();  
    
    function make_base_auth(user, password) {
      var tok = user + ':' + password;
      var hash = btoa(tok);
      return "Basic " + hash;
    }
    $.ajax
      ({
        type: "GET",
        url: "index1.php",
        dataType: 'json',
        async: false,
        data: '{}',
        beforeSend: function (xhr){ 
            xhr.setRequestHeader('Authorization', make_base_auth(username, password)); 
        },
        success: function (){
            alert('Thanks for your comment!'); 
        }
    });
    

提交回复
热议问题