ajax跨域(No 'Access-Control-Allow-Origin' header is present on the requested resource)


問題

在某域名下使用Ajax向另一個域名下的頁面請求數據,會遇到跨域問題。另一個域名必須在response中添加 Access-Control-Allow-Origin 的header,才能讓前者成功拿到數據。

這句話對嗎?如果對,那么流程是什么樣的?

跨域

怎樣才能算跨域?協議,域名,端口都必須相同,才算在同一個域。

 

當跨域訪問時,瀏覽器會發請求嗎

這是真正困擾我們的問題,因為我們不清楚瀏覽器會怎么做。它會不會檢查到你要請求的地址不是同一個域的,直接就禁止了呢? 瀏覽器確實發出了請求

我做了一個實驗,

前端(html)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ajax跨域</title>
<script src="https://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.ajax({
            url:'http://span.home.com/test.php',
            type:'POST',
            data:'name=hello',
            dataType:'json',
            success:function(data){
                alert(data.name);
            }
        });
    });
});
</script>
</head>
<body>

<div id="div1"><h2>使用 jQuery AJAX 獲取內容</h2></div>
<button>test</button>

</body>
</html>
View Code

后台(php)

<?php
header('content-type:application:json;charset=utf8'); 

$name = isset($_REQUEST['name']) ? $_REQUEST['name'] : 'will';
$arr = array('id'=>1, 'name'=>$name);

echo json_encode($arr);
View Code

控制台上會打出:

 XMLHttpRequest cannot load http://span.home.com/test.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://span.front.com' is therefore not allowed access. 

Access-Control-Allow-Origin

現在該 Access-Control-Allow-Origin 出場了。只有當目標頁面的response中,包含了 Access-Control-Allow-Origin 這個header,並且它的值里有我們自己的域名時,瀏覽器才允許我們拿到它頁面的數據進行下一步處理。如:

Access-Control-Allow-Origin:http://span.front.com

如果它的值設為 * ,則表示誰都可以用:

Access-Control-Allow-Origin: *

后台代碼作了部分修改之后就可以正常拿到頁面的數據:
<?php
header('content-type:application:json;charset=utf8'); 

$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
$allow_domain = array('http://span.front.com');

if (in_array($origin, $allow_domain))
{
    //Access-Control-Allow-Origin:* 表示允許任何域名跨域訪問 
    header('Access-Control-Allow-Origin:'.$origin);  
    header('Access-Control-Allow-Methods:GET,POST,OPTIONS');  
    header('Access-Control-Allow-Headers:x-requested-with,content-type');
}
$name = isset($_REQUEST['name']) ? $_REQUEST['name'] : 'will';
$arr = array('id'=>1, 'name'=>$name);

echo json_encode($arr);
View Code

注:前端域名 http://span.front.com, 后台域名 http://span.home.com

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM