2013-02-09 121 views
1

我正在做一個ajax請求來從webtrends檢索json數據 - 一種需要登錄的服務。我在我的ajax請求中傳遞用戶名和密碼,但仍然給我401未經授權的錯誤。我嘗試了3種不同的方法 - 但沒有運氣。有人可以幫我找到解決方案嗎?401(未經授權)ajax請求錯誤(需要用戶名和密碼)

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

對於***方法2 ***,你應該爲基地64編碼的字符串發送用戶名/密碼。這之前的SO貼子顯示瞭如何:http://stackoverflow.com/questions/11540086/jquery-ajax-header-authorisation – AardVark71 2013-02-09 14:22:41

回答

0

方法3當你要用一個回調函數可能會奏效,並在URL中使用基本身份驗證。不過請注意,很多瀏覽器都不接受url認證(或任何名稱)。如果你想嘗試它,你可以把它改寫這樣的:

window.onload = function() { 
var url = "https://xxx:[email protected]/...?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'); 
    } 
} 
+0

謝謝 - 我能夠得到它在FF和Chrome,但不是IE的工作。 – user1337813 2013-02-10 05:43:51

相關問題