10

我正在发出跨域 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);
            }
        });

当我提出此请求时,它会提示我输入凭据,并且我必须手动输入凭据才能获得响应。我们可以通过请求本身发送这些凭据吗?

4

3 回答 3

6

像下面的代码一样传递用户名和密码,

$.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,
});
于 2013-05-22T10:42:08.320 回答
5
$.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));             
    }
});
于 2014-01-15T11:01:41.127 回答
0
$.ajax({//No need to pass credentials 
            type: "get",
            async: false,
            url: "https://someurl/",
            xhrFields: {
                withCredentials: true
            },            
            success: function (data) {
                //do something
            }
        })
于 2021-06-23T12:05:10.440 回答