首页 文章

带有ajax请求的401(未授权)错误(需要用户名和密码)

提问于
浏览
1

我正在制作ajax请求以从webtrends中检索json数据 - 这是一项需要登录的服务 . 我在我的ajax请求中传递了用户名和密码,但仍然给了我401未经授权的错误 . 我尝试了3种不同的方法 - 但没有运气 . 有人可以帮我找到解决方案吗?

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');
                }
}

1 回答

  • 0

    当您使用命名回调函数并在URL中使用基本身份验证时, Method 3 可能会起作用 . 请注意,很多浏览器都不接受url-authentication(或者不管是什么名字) . 如果你想尝试一下,你可以像这样重写它:

    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');
      }
    }
    

相关问题