XHR (ajax) has cross origin instead of cross domain limit. It needs same host, same protocol and same port, otherwise it is cross origin, and we need turn to below 3 frequently used solutions to solve this issue.
Let's say http://abc.com javascript wants to do ajax call to http://xyz.com.
1. Server side proxy
abc.com should proxy the ajax request to http://xyz.com, so for browser, it is consider same origin.
2. JSONP
Include a script tag in http://abc.com, and the script is to ask for a JSONP response (basically json data wrapped in a callback javascript function) from http://xyz.com
Javascript callback in http://abc.com should process the response. http://xyz.com should set Content-type to application/javascript in http response header
e.g. Twitter supports JSONP
https://api.twitter.com/1/statuses/user_timeline/lucozhao.json?callback=updateTweets
3. CORS (Http access control)
Basically CORS is based on Http headers to communicate between browser and server
Request Headers:
Origin
Access-Control-Request-Method
Access-Control-Request-Headers
Response Headers:
Access-Control-Allow-Origin
Access-Control-Allow-Methods
Access-Control-Allow-Headers
Access-Control-Expose-Headers
Access-Control-Max-Age
Access-Control-Allow-Credentials
If server sends back Access-Control-Allow-Origin: * response header, then it allows ajax calls from other origins.
No comments:
Post a Comment