问题
I have looked at the following questions here on stackoverflow with no luck in what im trying to do.
Ajax Authorization Request headers fails again and again
jQuery Ajax Unauthorized 401 Error
Sending credentials with cross-domain posts?
Here is my code that I currently have:
$(document).ready(function() {
$.ajax({
url: 'http://sample.domain.com/script.php?name1=value1&jsonp=?',
type: 'GET',
dataType: 'json',
contentType: "application/json",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authentication", "Basic ZnJvbWFwcGx********uOnRoM24zcmQ1UmgzcjM=") //Some characters have been replaced for security but this is a true BASE64 of "username:password"
},
success: function(data){
alert(data);
}
});
});
</script>
The subdomain I have is password protected by an .htpasswd file. The login of the site works just fine for me using the username/password combo used in the base64 encode.
Im running this script on a different domain than the one that the url is on which is why i have the jsonp=? in the url
The response im getting from the console in the browser is:
GET http://sample.domain.com/script.php?name1=value1&jsonp=jsonp1334177732136 401 (Authorization Required)
回答1:
JSONP uses a script tag proxy. It wouldn't support custom headers. Are you in control of the endpoint? If so look into enabling CORS, or pass the authentication key in the GET string.
When using jsonp JQuery converts your URL "ajax" request to:
<script src="[endpoint]"></script>
it then writes a random function
var json9409d0sf0d9s0df90 = function() {
//some callback logic here.
}
and appends ?callback=json9409d0sf0d9s0df90
your server then says
echo $_GET['callback] . "(" . $json . ")";
and sends that back as the response so
json9409d0sf0d9s0df90({some: data});
is exexcuted by the browser and handled by jQuery's magical handlers that make it respond like a normal ajax callback.
AFAIK, <script src=""></script>
asset loads wont take custom headers by any standard browser.
回答2:
The header name is Authorization
, and you are sending "Authentication
"
e.g.
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtBmU=
来源:https://stackoverflow.com/questions/10113911/sending-authorization-headers-with-jquery-and-ajax