Trouble with jquery ajax and safari when passing a username/password
We are trying to pass credentials to our site via jquery ajax (not using php [yeah I know this is unsafe]).
It seems Safari is having trouble with the username
/password
attributes of the ajax method. (jquery ajax) We are using jquery 1.5.1
.
Here is example code:
$.ajax({
url: "/some/url",
type: 'GET',
cache: true,
dataType: 'json',
processData: false,
data: 'get=login',
timeout: 7000,
username: "user",
pass开发者_运维问答word: "pass",
success: function (data, textStatus, response) {
Log("success");
},
error: function (data, textStatus, response) {
Log("fail");
}
});
This works fine in Firefox, Chrome, and IE7/8, but Safari won't even send the ajax to the server (did a trace with wireshark and nothing is going down the pipe). Strangely enough, the error
function gets called.
If I comment out username and password, the ajax is sent.
Is more simple:
$.ajax({
url: "/some/url",
type: 'GET',
cache: true,
dataType: 'json',
processData: false,
data: 'get=login',
timeout: 7000,
headers: {
"Authorization": "Basic " + Base64.encode("username:password")
},
success: function (data, textStatus, response) {
Log("success");
},
error: function (data, textStatus, response) {
Log("fail");
}
});
This works for me.
Greetings
I was able to fix this problem by using beforeSend
and creating a request header. Apparently if this isn't included, Safari chokes and doesn't send anything. Here's the code:
$.ajax({
url: "/some/url",
type: 'GET',
cache: true,
dataType: 'json',
processData: false,
data: 'get=login',
timeout: 7000,
username: "user",
password: "pass",
beforeSend: function (req) {
req.setRequestHeader('Authorization', "Basic " + btoa("user:password"));
}
success: function (data, textStatus, response) {
Log("success");
},
error: function (data, textStatus, response) {
Log("fail");
}
});
Have you seen the anti-phising warning that Safari displays when you click on a URL containing a username and password?
http://username:password@example.com/
It's likely that it's the same thing that's preventing your AJAX request from even being sent (as it won't actually load the site, and hence send the request, until you click the Ignore button).
Try loading the AJAX request in the main browser, click "Ignore Warning" and then try the AJAX request again to see if it fires.
I just noticed that putting "@" in the username or password results in the same behavior you're experience. Safari seems to be picky about what characters you can use...
精彩评论