I am attempting to call this web service: http://www.civicapps.org/datasets/restaurant-inspections
Here’s my code:
<script>
$(document).ready(function() {
function showInspections() {
var data = $.ajax({
type : 'GET',
url : '//api.civicapps.org/restaurant-inspections/',
async : false,
dataType : 'json',
success: function(data){
if(data.status == "ok"){
alert(data);
}
}
});
}
showInspections();
});
</script>
Firebug Net>XHR shows “200 Status OK” and yet there is no response with the JSON data. Likewise, Console tab shows the same GET request and status but the text for it is in red.
Questions:
- Am I failing to receive the response data in JSON due to cross-domain issues i.e. the data should be sent in JSONP rather than JSON? If so, is there a way to get around this solely from my end, assuming the response will not be sent in JSONP?
- What does the red text in Firebug console indicate?
Am I failing to receive the response data in JSON due to cross-domain issues i.e. the data should be sent in JSONP rather than JSON?
Yes. JSONP is actually very different than “JSON” (i.e. an AJAX request that returns JSON-formatted data). Even though the responses look very similar and the implementation in jQuery is very similar (just add a ‘p’!), the actual architecture of JSONP is very different. In fact, JSONP is not even AJAX (if by AJAX you mean something that uses
XMLHttpRequest). JSONP gets around cross-domain issues by using a trick involving a dynamically generated<script>element.If so, is there a way to get around this solely from my end, assuming the response will not be sent in JSONP?
Fortunately, no. While this may be unfortunate for you, it’s fortunate for the web. Because if you could get around cross-domain issues from the client side, the web would be far less secure. Imagine you went to my website and some hidden JavaScript downloaded all your new emails from Gmail, parsed them, then sent them to my server. That would be possible if not for the same-origin policy.
JSONP is nice because it offers a workaround for cross-origin requests that services can opt-in to. If a service wants to be accessible cross-domain, then it can be written in JSONP. This prevents unwitting cross-domain services while allowing for services to volunteer cross-domain availability.
What does the red text in Firebug console indicate?
It probably indicates a violation of the same-origin policy.