使用 jQuery 进行 Ajax 身份验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10226333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ajax authentication with jQuery
提问by Fotis Adamakis
I'm able to recieve the requested xml with
我能够收到请求的 xml
curl -X GET -u username:password url
but not with
但不是与
$.get('url',
{username:"username",password:"password"},
function (data) {
});
No javascript errors, no cross domain policy issues. It might be a syntax error but I failed to find a decent tutorial yet. Any suggestions please?
没有 javascript 错误,没有跨域策略问题。这可能是一个语法错误,但我还没有找到一个像样的教程。请问有什么建议吗?
回答by Royi Namir
I think you'd need the plain format :
我认为您需要纯格式:
$.ajax({
type: 'GET',
url: 'url',
dataType: 'json',
//whatever you need
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', make_base_auth(user, password));
},
success: function () {});
});
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return 'Basic ' + hash;
}
回答by Stuart Hallows
As an alternative to beforeSend
you could use the headers
property to add the authorization
header.
作为替代方案,beforeSend
您可以使用该headers
属性添加authorization
标题。
$.ajax({
type: 'GET',
url: 'url',
dataType: 'json',
headers: {
"Authorization": make_base_auth(user, password)
}
success: function () {});
});
回答by Satish
As pointed in the other answer, you should be using beforeSend function of Jquery Ajax to add authorization header
正如另一个答案中所指出的,您应该使用 Jquery Ajax 的 beforeSend 函数来添加授权标头
function setAuthHeader(xhr){
var creds = username + ':' + password;
var basicScheme = btoa(creds);
var hashStr = "Basic "+basicScheme;
xhr.setRequestHeader('Authorization', hashStr);
}
$.get('url',
beforeSend: setAuthHeader,
function (data) {
});