401(未经授权)ajax请求错误(需要用户名和密码)
我正在发出一个ajax请求,从webtrends检索json数据,这是一个需要登录的服务。我在ajax请求中传递用户名和密码,但仍然会给我一个错误。我试过3种不同的方法,但都不走运。有人能帮我找到解决办法吗401(未经授权)ajax请求错误(需要用户名和密码),ajax,jsonp,http-status-code-401,Ajax,Jsonp,Http Status Code 401,我正在发出一个ajax请求,从webtrends检索json数据,这是一个需要登录的服务。我在ajax请求中传递用户名和密码,但仍然会给我一个错误。我试过3种不同的方法,但都不走运。有人能帮我找到解决办法吗 1. $.getJSON('https://ws.webtrends.com/..?jsoncallback=?', { format: 'jsonp', suppress_error_codes: 'true', username: 'xxx', password: 'xxx', ca
1. $.getJSON('https://ws.webtrends.com/..?jsoncallback=?', { format: 'jsonp', suppress_error_codes: 'true', username: 'xxx', password: 'xxx', cache: 'false' }, function(json) {
console.log(json);
alert(json);
});
2. $.ajax({
url: "https://ws.webtrends.com/../?callback=?",
type: 'GET',
cache: false,
dataType: 'jsonp',
processData: false,
data: 'get=login',
username: "xxx",
password: "xxx",
beforeSend: function (req) {
req.setRequestHeader('Authorization', "xxx:xxx");
},
success: function (response) {
alert("success");
},
error: function(error) {
alert("error");
}
});
3. window.onload=function() {
var url = "https://ws.webtrends.com/...?username=xxx&password=xxx&callback=?";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
function parseRequest(response) {
try {
alert(response);
}
catch(an_exception) {
alert('error');
}
}
当您使用命名回调函数并在url中使用基本身份验证时,方法3可能会起作用。请注意,很多浏览器都不接受url身份验证(或其他名称)。如果您想尝试,可以这样重写:
window.onload = function() {
var url = "https://xxx:xxx@ws.webtrends.com/...?callback=parseRequest";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
function parseRequest(response) {
try {
alert(response);
}
catch(an_exception) {
alert('error');
}
}
对于方法2,您应该将用户名/密码作为base 64编码字符串发送。前一篇SO帖子展示了如何:谢谢——我能够让它在FF和Chrome中工作,但不是IE。