I inadvertently wrote a cross-domain AJAX call to NextBus (with jQuery):
$.ajax({
url: 'http://webservices.nextbus.com/service/publicXMLFeed?command=predictions&a=sf-muni&r=1&s=6294',
dataType: 'xml',
success: function(data) {
do_stuff();
}
});
Thing is, it works on all browsers, despite coming from a different domain. Given the Single Origin Policy, why does this actually work?
The page is here: http://sftransitfirst.org/F/, selecting a stop from the pull-down triggers the ajax.
As expected, making a similar call to the Google Maps API Web Services fails with the familiar Origin ... is not allowed by Access-Control-Allow-Origin
(and it doesn't support jsonp).
CORS is a mechanism that defines a procedure in which the browser and the web server interact to determine whether to allow a web page to access a resource from different origin. Figure 2. Cross domain ajax request. When you do a cross-origin request, the browser sends Origin header with the current domain value.
You can allow Cross Domain Ajax calls to an application by just registering a new filter and then configure it to Allow-Origin : {your domain's} or you can use a wild card “*” to allow the calls from all domains.
Cross-origin resource sharing (or CORS) can be used to make AJAX requests to another domain.
How AJAX Calls Work. AJAX uses both a browser built-in XMLHttpRequest object to get data from the web server and JavaScript and HTML DOM to display that content to the user. Despite the name “AJAX” these calls can also transport data as plain text or JSON instead of XML.
They must have explicitly allowed cross-domain access, with something of this manner:
<?php header('Access-Control-Allow-Origin: *'); ?>
Or with htaccess:
<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin: *
</ifModule>
Many modern web APIs enable Cross-Domain Resource Sharing (CORS). CORS is a method for websites to voluntarily make their pages available to cross-domain scripts. The Access-Control-Allow-Origin
HTTP header from the server signals to your web browser that it is okay to allow the script to access the page with Ajax, even if the script is running on a different origin. If the server does not serve CORS headers, your browser will enforce the SOP as usual.
Most APIs choose to expose their pages to cross-domain scripts because they know that virtually all of their users will want to be able to access the API via Ajax from their own domains.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With