2013-05-22 61 views
10

我正在進行跨域ajax請求來獲取一些數據。 REST服務有Basic authentication(通過IIS設置)。跨域ajax請求基本認證

$.ajax({ 
      type: "GET", 
      xhrFields: { 
       withCredentials: true 
      }, 
      dataType: "jsonp", 
      contentType: "application/javascript", 
      data: myData, 
      async: false, 
      crossDomain: true, 
      url: "http://xx.xx.xx.xx/MyService/MyService.svc/GetData", 
      success: function (jsonData) { 
       console.log(jsonData); 
      }, 
      error: function (request, textStatus, errorThrown) { 
       console.log(request.responseText); 
       console.log(textStatus); 
       console.log(errorThrown); 
      } 
     }); 

當我提出這個要求,它會提示我輸入憑據&我必須手動輸入憑據獲得響應。我們可以通過請求本身發送這些憑據嗎?

回答

5

通行證用戶名和像下面的代碼密碼,

$.ajax({ 
    type: "GET", 
    xhrFields: { 
     withCredentials: true 
    }, 
    dataType: "jsonp", 
    contentType: "application/javascript", 
    data: myData, 
    async: false, 
    crossDomain: true, 
    url: "http://xx.xx.xx.xx/MyService/MyService.svc/GetData", 
    success: function (jsonData) { 
     console.log(jsonData); 
    }, 
    error: function (request, textStatus, errorThrown) { 
     console.log(request.responseText); 
     console.log(textStatus); 
     console.log(errorThrown); 
    } 
    username: username, 
    password: password, 
}); 
4
$.ajax({ 
    url: 'yoururl', 
    username : username, 
    password :password, 
    type: 'POST', 
    contentType: 'application/x-www-form-urlencoded', 
    dataType: "text", 
    xhrFields: 
    { 
     withCredentials: true 
    }, 
    beforeSend: function (xhr) { 
     xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));    
    } 
}); 
+2

我並不對此感到興奮的答案,這裏的原因:它是多餘的(問題被回答了爲期半年的更早),它是多餘的(jQuery爲你處理auth的東西,AFAICT)。如果我對後者有錯,請編輯答案,我將刪除此評論。 –

+0

使用beforeSend屬性爲我工作,因爲用戶名和密碼由於某種原因沒有添加授權標頭。以防萬一它幫助任何人。 – rodrigobartels