我正在寻找这个问题差不多3个小时。
所以我在开发我的应用程序时使用codeigniter。
所以我想在这个url'login / loguser'
中发出一个AJAX请求但是,它表示请求的资源上没有“Access-Control-Allow-Origin”标头。因此,不允许原点“http://ssmis.wc.lt”访问。
我知道你会说我应该把header()放在访问控制源上。所以我已经完成了这个
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class LogIn extends Ss_Controller{
function __construct(){
//So in case we have to do something in the constructor we dont override the parent constructor.
parent::__construct();
}
function index(){
$data['title'] = "Login";
$data['page_content'] = "login_view.php";
$extra_css = array(
"http://fonts.googleapis.com/css?family=Play",
"public/system_css/login.css",
);
$data['extra_css'] = $extra_css;
$extra_js = array(
"public/system_js/modules/main.js",
"public/system_js/login.js",
"public/system_js/modules/login_module.js"
);
$data['extra_js'] = $extra_js;
$this->load->view('includes/template.php',$data);
}
function loguser(){
header("Access-Control-Allow-Origin: *");
$data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter
$this->load->model('usermod');
$validated = $this->usermod->validate_credentials($data);
//when $result returns true redirect to home page.
if($validated){
//set sessions cookies.
$data = array(
"username" => $data['batch_id'],
"is_logged_in" => true
);
$this->session->set_userdata($data);
//redirect to home page.
$response['success'] = true;
$this->echo_response($response,200,'OK');
}else{
//redirect to log-in page with error message
$response['success'] = false;
$this->echo_response($response,201,'Not OK!');
}
}
}
这是我的ajax代码:
var login = function login(formdata){
$.ajax({
type: 'POST',
url: Main.Vars.host + 'login/loguser',
contentType: false,
headers: { 'Access-Control-Allow-Origin': '*' },
crossDomain: true,
cache: false,
processData:false,
data: formdata,
dataType: 'json',
success: function(data){
if(data.success == true){
window.location.assign(Main.Vars.host + "home/");
}else{
alert("Cannot logged in!");
}
}
});
};
正如你所看到的,我已经在我的ajax调用和我的控制器类中放入了Access-Control-Allow-Origin,因为我现在非常绝望。
我还尝试将标题放在我的自定义Base_Controller上,如下所示:
这是我的Base_Controller,它扩展了CI_Controller
//echo response in json format.
public function echo_response($data, $code, $status_message){
$this->output->set_header('Content-Type: application/json; charset=utf-8');
$this->output->set_header('Access-Control-Expose-Headers: Access-Control-Allow-Origin');
$this->output->set_status_header($code, $status_message);
echo json_encode($data);
}
我尝试了所有我研究过的东西,但仍然没有运气。执行ajax调用时,访问COntrol允许Origin头仍然不存在。我真的需要帮助。
PS我也在ajax中尝试了jsonp但是给了我错误。
谢谢!