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
ajaxObj
我在使用 setRequestHeader 的函数中做错了吗?第一次做跨站php代码。我只是想弄清楚为什么我的代码没有为 ACAO 正确执行