要解决在CodeIgniter中阻止AJAX的CORS问题,可以按照以下步骤进行操作:
在CodeIgniter项目的根目录中,创建一个名为.htaccess
的文件(如果已经存在,请跳过此步骤)。
在.htaccess
文件中添加以下代码来启用CORS:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
public function my_ajax_method() {
// 允许跨域请求
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: origin, x-requested-with, content-type");
// 处理AJAX请求
// ...
}
withCredentials: true
选项:$.ajax({
url: 'http://example.com/my_ajax_method',
type: 'POST',
xhrFields: {
withCredentials: true
},
// ...
});
通过按照以上步骤操作,您应该能够在CodeIgniter中解决AJAX阻止CORS问题。