我正在制作跨域ajax请求以获取一些数据。 REST服务具有Basic authentication
(通过IIS
设置)。
$.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);
}
});
当我提出此请求时,它会提示我输入凭据&我必须手动输入凭据才能获得响应。我们可以通过请求本身发送这些凭据吗?
答案 0 :(得分: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,
});
答案 1 :(得分: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 :(得分:0)
$.ajax({//No need to pass credentials
type: "get",
async: false,
url: "https://someurl/",
xhrFields: {
withCredentials: true
},
success: function (data) {
//do something
}
})