Cross-Domain Ajax Request Blocked by Access-Control-Allow-Origin
This issue arises when an Ajax request attempts to access a resource from a different domain, triggering the Access-Control-Allow-Origin error. In this specific instance, the Ajax request is being made to a remote PHP server from a Sencha Touch 2 application.
Addressing the Issue
To resolve this error and allow cross-domain Ajax, the server must be configured to add a response header for Access-Control-Allow-Origin. This header specifies the allowed domains that can make Ajax requests.
In PHP, this can be achieved by modifying the response header as follows:
header('Access-Control-Allow-Origin: *');
Additional Options
Apache Configuration or .htaccess:
If you have access to the Apache configuration file or .htaccess file, you can also set the header there:
Header set Access-Control-Allow-Origin *
Caution:
While enabling cross-domain Ajax allows for more flexibility, it also disables CORS protection, which can leave users vulnerable to attacks. Use the wildcard (*) only if absolutely necessary. Instead, it's recommended to whitelist specific domains as demonstrated in the provided PHP code sample.
The above is the detailed content of How to Enable Cross-Domain Ajax Requests and Avoid Access-Control-Allow-Origin Errors?. For more information, please follow other related articles on the PHP Chinese website!