错误:No' Access-Control-Allow-Origin'标头出现在请求的资源上

时间:2015-11-17 06:47:27

标签: php

我有两个系统helpdesk.ops.something.indev1.ops.something.in

我在helpdesk.ops中有一个文件fetchP.php,其代码如下:

<?php
header('Access-Control-Allow-Origin: *');
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
    function someFunc(item) {
        $.ajax({method:"GET", 
        url:"http://dev1.ops.something.in/wallet/createurl.php?phone="+item, 
        success:function(response){
            console.log(response);
        }
        });
    };
</script>';
<?php
echo '<div id="callToWallet" class="sample-button" onclick="someFunc(911234567890);"><a href="#"> Click here</a></div>';

正在对dev1.ops中存在的文件createurl.php执行GET请求,如下所示:

<?php
header('Access-Control-Allow-Origin: *');?>
<script>response.addHeader("Access-Control-Allow-Origin", "*");</script>
<?php 
// the rest of the code
?>

但是在执行时,GET请求不成功,我收到错误:

XMLHttpRequest cannot load http://dev1.ops.something.in/wallet/createurl.php?phone=911234567890. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://helpdesk.ops.something.in' is therefore not allowed access. The response had HTTP status code 500.

我错过了什么?

1 个答案:

答案 0 :(得分:11)

即使设置了Access-Control-Allow-Origin标头,XMLHttpRequest也无法请求与您当前域不同的域上的资源(这是由于same-origin policy)。

您可以尝试绕过它的一种方法是使用JSONP。这是一个简单而简单的例子:

fetchP.php(Ajax电话会议):

function someFunc(item) {
    $.ajax({
        method: "GET",
        data: { phone: item },
        url: "http://localhost:2512/createurl.php", 
        success: function(response){
            console.log(response);
        },
        dataType: "jsonp",
    });
};

createurl.php

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

  $data = ["foo" => "bar", "bar" => "baz"];
  $json = json_encode($data);

  $functionName = $_GET['callback'];

  echo "$functionName($json);";
?>

ajax请求上createurl.php的示例输出:

jQuery2130388456100365147_1447744407137({"foo":"bar","bar":"baz"});

然后jQuery执行已定义的函数并在给定参数上调用定义的success方法(在本例中为JSON)。