CORS不工作的PHP

我正试图通过CORS将表单数据从www.siteone.com发布到www.sitetwo.com。 我的ajax代码是这样的:

<script> $(document).ready(function(){ $("#submit").live('click',function() { var url = "http://www.sitetwo.com/cors.php"; var data = $('#form').serialize(); jQuery.ajax({ url : url, type: "POST", data : $('#form').serialize(), }).done(function(response){ alert(response); }).fail(function(error){ console.log(error.statusText); }); return false; }); }); </script> 

www.sitetwo.com上的cors.php文件如下:

 <?php header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); echo "hai"; ?> 

但仍然存在Access-control-Allow-Origin错误。 抛出的错误是这样的:

 XMLHttpRequest cannot load http://www.sitetwo.com/cors.php. Origin http://www.siteone.com is not allowed by Access-Control-Allow-Origin. 

我开始知道,只需通过头信息允许远程网站使用CORS,就可以使用跨域请求。 但是,当我这样试图,错误抛出。 我错过了什么吗? 这是我的请求/响应标题:

 Response Headers Connection Keep-Alive Content-Length 487 Content-Type text/html; charset=iso-8859-1 Date Fri, 23 Aug 2013 05:53:20 GMT Keep-Alive timeout=15, max=99 Server Apache/2.2.15 (CentOS) WWW-Authenticate Basic realm="Site two Server - Restricted Area" Request Headers Accept */* Accept-Encoding gzip, deflate Accept-Language en-US,en;q=0.5 Content-Length 43 Content-Type application/x-www-form-urlencoded; charset=UTF-8 Host www.sitetwo.com Origin http://www.siteone.com Referer http://www.siteone.com/index.html User-Agent Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:23.0) Gecko/20100101 Firefox/23.0 

最后,我自己解决了问题中解释的问题。 我已经实现访问标头的代码是不正确的。

下面提到的两行代码在给定时不起作用:

 <?php header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); ?> 

但是,正确处理CORS请求涉及更多。 这是一个function,将更全面地回应。 更新的代码是这样的:

  <?php // Allow from any origin if (isset($_SERVER['HTTP_ORIGIN'])) { header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Max-Age: 86400'); // cache for 1 day } // Access-Control headers are received during OPTIONS requests if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); exit(0); } echo "You have CORS!"; ?> 

我从另一个postfind它的工作….