Use basic authentication with jQuery and Ajax

前端 未结 10 1079
野的像风
野的像风 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 06:56

    There are 3 ways to achieve this as shown below

    Method 1:

    var uName="abc";
    var passwrd="pqr";
    
    $.ajax({
        type: '{GET/POST}',
        url: '{urlpath}',
        headers: {
            "Authorization": "Basic " + btoa(uName+":"+passwrd);
        },
        success : function(data) {
          //Success block  
        },
       error: function (xhr,ajaxOptions,throwError){
        //Error block 
      },
    });
    

    Method 2:

    var uName="abc";
    var passwrd="pqr";
    
    $.ajax({
        type: '{GET/POST}',
        url: '{urlpath}',
         beforeSend: function (xhr){ 
            xhr.setRequestHeader('Authorization', "Basic " + btoa(uName+":"+passwrd)); 
        },
        success : function(data) {
          //Success block 
       },
       error: function (xhr,ajaxOptions,throwError){
        //Error block 
      },
    });
    

    Method 3:

    var uName="abc";
    var passwrd="pqr";
    
    $.ajax({
        type: '{GET/POST}',
        url: '{urlpath}',
        username:uName,
        password:passwrd, 
        success : function(data) {
        //Success block  
       },
        error: function (xhr,ajaxOptions,throwError){
        //Error block 
      },
    });
    

提交回复
热议问题