Access-Control-Allow-Origin不允许XMLHttpRequest

时间:2013-08-25 04:54:38

标签: php javascript ajax

PHP:

<?php
  header('Access-Control-Allow-Origin: *');
    include_once("db_connect.php");
    $username = '';
    $video = '';
    $rating ='';
if(isset($_GET["u"])){
 $username = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
 } else {
 echo "No UserName";
}
 if(isset($_GET["v"])){
  $video= preg_replace('#[0-9]#i','',$_GET['v']);
 } else {
 echo "No Video ID";
}
 ...
 ?>

JavaScript的:

function like(u,v) {
  document.getElementById("rating").innerHTML="loading...";
var ajax = ajaxObj("POST","http://www.url.com/ratingphp.php");
 ajax.onreadystatechange=function(){
  if(ajaxReturn(ajax) === true){
  document.getElementById("rating").innerHTML=ajax.responseText;
  }
};
ajax.send("u="+u+"&v="+v+"&like");
}

function dislike(u,v) {
 document.getElementById("rating").innerHTML="loading...";
var ajax = ajaxObj("POST","http://www.url.com/ratingphp.php");
ajax.onreadystatechange=function(){
  if(ajaxReturn(ajax) === true){
document.getElementById("rating").innerHTML=ajax.responseText;
  }
 };
 ajax.send("u="+u+"&v="+v+"&dislike");
}


function ajaxObj(meth,url){
  var x= new XMLHttpRequest();
  x.open(meth,url,true);
  x.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  return x;
 }
function ajaxReturn(x){
 if(x.readyState == 4 && x.status == 200){
  return true;
  }
 }

因为你可以看到我在我的PHP中允许Access-Control-Allow-Origin,但我一直收到错误:

XMLHttpRequest cannot load http://www.url.com/ratingphp.php. Origin http://www.url2.com is not allowed by Access-Control-Allow-Origin. h37:1

我使用setRequestHeader在我的ajaxObj函数中做错了什么?第一次做一个跨站点的PHP代码。我只想弄清楚为什么我的代码没有为ACAO正确执行

2 个答案:

答案 0 :(得分:0)

只需在PHP中添加..

header("Access-Control-Allow-Headers : Content-Type");
header("Access-Control-Allow-Methods : POST, OPTIONS");

答案 1 :(得分:0)

header('Access-Control-Allow-Origin: *');