Javascript: handling with crossdomain requests
posted in /home/JavaScript on 2011-01-19 |
Ajax is a powerful tool for loading new content or data asynchronously. The well known problem is that we can't make requests to other hosts. In other words if your code is located at aaa.com you can't load bbb.com/getData.php. There are several solutions available.
1. Using frameworks
One of the popular solutions is to use some of the nice frameworks like jQuery that will do the job for you. jQuery supports native crossdomain requests. For more information check this page.
2. Using server-side code as a proxy
The other method that I prefer is to use some server-side language as a proxy. For example if you need to access bbb.com from aaa.com you can create a php file aaa.com/getDataFromBBB.php. This file is on your domain and you have access to it. Then you can simply use curl to access bbb.com and return the result to your local javascript code.
3. Using server's proxy
This is the ideal solution, but of course you have to have an administration access to your server. For example Apache has a module called mod_proxy, which perfectly fits in our needs. The basic idea is to add a rule that will forward your requests from aaa.com to bbb.com.
For example if you try to open aaa.com/data/getData.php the server will automatically open http://bbb.com/data/getData.php
1. Using frameworks
One of the popular solutions is to use some of the nice frameworks like jQuery that will do the job for you. jQuery supports native crossdomain requests. For more information check this page.
2. Using server-side code as a proxy
The other method that I prefer is to use some server-side language as a proxy. For example if you need to access bbb.com from aaa.com you can create a php file aaa.com/getDataFromBBB.php. This file is on your domain and you have access to it. Then you can simply use curl to access bbb.com and return the result to your local javascript code.
3. Using server's proxy
This is the ideal solution, but of course you have to have an administration access to your server. For example Apache has a module called mod_proxy, which perfectly fits in our needs. The basic idea is to add a rule that will forward your requests from aaa.com to bbb.com.
For example if you try to open aaa.com/data/getData.php the server will automatically open http://bbb.com/data/getData.php
Delicious