我试图通过浏览器创建一个基本的身份验证,但我真的无法到达那里。
如果这个脚本不在这里,浏览器将接管身份验证,但我想告诉浏览器用户即将进行身份验证。
地址应该是这样的:
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!');
}
});
有3种方法可以实现这一点,如下所示
方法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
},
});
方法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
},
});
方法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
},
});
一年中事情发生了怎样的变化。除了头属性的位置xhr。setRequestHeader,当前jQuery(1.7.2+)包含用户名和密码属性。ajax调用。
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
username: username,
password: password,
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});
从评论和其他答案编辑:为了在没有401 Unauthorized响应的情况下先发制人地发送身份验证,而不是setRequestHeader (pre -1.7)使用'headers':
$.ajax
({
type: "GET",
url: "index1.php",
dataType: 'json',
headers: {
"Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
},
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});