使用 jQuery 和 Ajax 进行基本身份验证
我正在尝试通过浏览器创建基本身份验证,但我无法真正做到.
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 over, but I want to tell the browser that the user is about to make the authentication.
地址应该是这样的:
http://username:password@server.in.local/
我有一个表格:
<form name="cookieform" id="login" method="post">
<input type="text" name="username" id="username" class="text"/>
<input type="password" name="password" id="password" class="text"/>
<input type="submit" name="sub" value="Submit" class="page"/>
</form>
还有一个脚本:
var username = $("input#username").val();
var password = $("input#password").val();
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
async: false,
data: '{"username": "' + username + '", "password" : "' + password + '"}',
success: function (){
alert('Thanks for your comment!');
}
});
推荐答案
使用jQuery的beforeSend
回调添加带有身份验证信息的 HTTP 标头:
Use jQuery's beforeSend
callback to add an HTTP header with the authentication information:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},
相关文章