簡體   English   中英

錯誤:請求的資源上沒有“Access-Control-Allow-Origin”標頭

[英]Error: No 'Access-Control-Allow-Origin' header is present on the requested resource

我有兩個系統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>';

這是對createurl.php存在的文件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.

我錯過了什么?

即使設置了Access-Control-Allow-Origin標頭,XMLHttpRequest也不能在與您當前域不同的域上請求資源(這是由於同源策略 )。

你可以嘗試解決它的一種方法是使用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)。

暫無
暫無

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

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