AJAX was a boon to web development and web applications like GMail etc. millions of site have since implemented AJAX based features on their websites, the idea of asynchronously accessing content was wonderful but AJAX was limited only to the same domain (same origin) as the page requesting the content. Cross-Origin Resource Sharing brought an end to this limitation where the remote server can allow/deny any domain on it's discretion.
Now using 3rd party resources via AJAX is easier & secure. Almost all the current web browsers (Firefox, IE, Chrome, Safari, Opera, etc.) support CORS so there's not much need to worry about compatibility, for an exhaustive TOC of browser compatibility visit http://caniuse.com/#feat=cors. In this article we'll look at how CORS works & and how to implement it.
CORS adds new HTTP headers to request/server resources to allowed domains. It's the browser's responsibility to check and enforce restrictions, the browser when it encounters the first cross-origin request, checks with the target domains using the HTTP OPTIONS method for permissions to access the resource, in response servers will tell the allowed domains, and may also specify additional data (like cookies, basic auth) required for the requests.
As I said earlier the CORS request is just like the normal AJAX request, follow the examples below, in my examples I have used jQuery instead of native JS for ease.
That's all that need to get CORS working, rest all is regular AJAX, get started and keep us posted in case you have any problems.
|All times are GMT +5.5. The time now is 14:32.|