Reputation: 3236
I'm trying to use an API which requires a call to get a Json with basic HTTP authentication. I'm not brilliant with javascript.
The code which I have is:
<script type="text/javascript">
$.getJSON({
'url': 'http://data.unistats.ac.uk/api/KIS/Institutions.JSON?pageIndex=1&pageSize=25',
'beforeSend': function(xhr) {
xhr.setRequestHeader("Authorization",
"Basic " + encodeBase64("ABCDEF" + ":" + password));
},
success: function(result) {
alert('done');
},
error: function(result) {
alert('no');
}
});
</script>
I expect that this would call one of either success, or error. So the output should be either an alert saying "done", or an alert saying "no". Or even an error in the developer console to tell me what is wrong.
I don't get anything, neither alert shows and I have no errors in the console. Any ideas what is happening here?
Thanks,
Edit: Using firebug I see the request headers are: The request headers show up as:
OPTIONS /api/KIS/Institutions.JSON?pageIndex=1&pageSize=25 HTTP/1.1
Host: data.unistats.ac.uk
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: null
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization
Connection: keep-alive
This doesn't seem correct as it should be: Authorization: basic TheSecurityKey
The response is 405, method not allowed Reload the page to get source for: http://data.unistats.ac.uk/api/KIS/Institutions.JSON?pageIndex=1&pageSize=25
Response headers:
HTTP/1.1 405 Method Not Allowed
Cache-Control: private
Allow: GET
Content-Length: 1725
Content-Type: text/html; charset=UTF-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 16 Aug 2013 21:00:11 GMT
When I try from a server I have set up
Can be seen here: http://spindroid.co.uk/tt/byUniversity.html
Partial Solution
Using jsonp it receives a response, but the headers aren't attached and so I am missing authentication.
<script type="text/javascript">
$(document).ready(function () {
jQuery.support.cors = true;
$.ajax({
'type': "GET",
'dataType': 'jsonp',
'url': 'https://data.unistats.ac.uk/api/KIS/Institutions.JSON?pageIndex=1&pageSize=25',
'beforeSend': function(xhr) {
xhr.setRequestHeader("Authorization",
"Basic " + btoa("AAA"));
console.error("Basic " + btoa("AAA"));
},
success: function(result) {
alert('done');
},
error: function(jqXHR, status, error){ console.log(status, error); }
});
}
); </script>
Upvotes: 2
Views: 2280
Reputation: 700262
The getJSON
method doesn't take an object with settings. Use the ajax
method instead, and specify dataType: 'json'
as one of the settings.
Upvotes: 7