2013-05-22 32 views
10

私はクロスドメインのajaxリクエストを作成してデータを取得しています。 RESTサービスはBasic authenticationIISで設定)です。クロスドメイン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

何らかの理由でユーザー名とパスワードがAuthorizationヘッダーを追加していなかったため、beforeSendプロパティを使用してくれました。ちょうどそれが誰のためにも役立ちます。 – rodrigobartels