PHP & ajax

$.ajax({
url: '//www.gocar.idv.tw/tset/test.php',     
cache:false,      
async:false,     
type: "POST",     
dataType: 'json',     
data: '&key='+key ,     
success: function (data) {          
    $.each(data, function(index, val) {                   
    });
}, error:function(msg){         
      alert('錯誤!'+msg);     
    } 
});

[PHP]Ajax CORS 錯誤

有時在串接Ajax會看到下列錯誤

Access to XMLHttpRequest at 'https://url/test.php' from origin 'http://url' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

錯誤訊息主要是說ajax要連線的網址被瀏覽器的同源政策阻擋(CORS policy)
簡單來說就是ajax連線網址跟現在正在瀏覽網頁的網址不一樣
(就算是http跟https也視同不一樣)
所以ajax連線的程式就要設定Header開放跨網域連線


if($_SERVER['HTTP_ORIGIN'] == "http://URL_A") {
    header('Access-Control-Allow-Origin: http://URL_A');
}else if($_SERVER['HTTP_ORIGIN'] == "https://URL_A") {
    header('Access-Control-Allow-Origin: https://URL_A');
}else if($_SERVER['HTTP_ORIGIN'] == "http://URL_B") {
    header('Access-Control-Allow-Origin: http://URL_B');
}else {
	echo "no auth";
	exit;
}

如果要開放讓所有網域連線的話,設為 * 就可以了

header("Access-Control-Allow-Origin: *");