簡體   English   中英

Access-Control-Allow-Origin 不允許 XMLHttpRequest

[英]XMLHttpRequest is not allowed by Access-Control-Allow-Origin

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 正確執行

只需在 PHP 中添加這個 ..

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM