Use basic authentication with jQuery and Ajax

前端 未结 10 1046
野的像风
野的像风 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:55

    How things change in a year. In addition to the header attribute in place of xhr.setRequestHeader, current jQuery (1.7.2+) includes a username and password attribute with the $.ajax call.

    $.ajax
    ({
      type: "GET",
      url: "index1.php",
      dataType: 'json',
      username: username,
      password: password,
      data: '{ "comment" }',
      success: function (){
        alert('Thanks for your comment!'); 
      }
    });
    

    EDIT from comments and other answers: To be clear - in order to preemptively send authentication without a 401 Unauthorized response, instead of setRequestHeader (pre -1.7) use 'headers':

    $.ajax
    ({
      type: "GET",
      url: "index1.php",
      dataType: 'json',
      headers: {
        "Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
      },
      data: '{ "comment" }',
      success: function (){
        alert('Thanks for your comment!'); 
      }
    });
    

提交回复
热议问题