Why does this cross-domain ajax call actually work

2019-04-28 22:31发布

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).

2条回答
劫难
2楼-- · 2019-04-28 22:39

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.

查看更多
孤傲高冷的网名
3楼-- · 2019-04-28 22:40

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>
查看更多
登录 后发表回答