close

上次發現ajax在存取上有跨網域的問題後,就一直想試看看解決的方法,
為了安全性考量,在跨網域存取時,必須得到對方網域的同意才能存取。
所以到網路下載一個免安裝的Apache+MySQL的程式:UniServerZ
解壓縮後,直接執行就可以開啟Apache Web Site,很方便測試。

先寫一個簡單PHP網頁test01.php:
<?php
echo "我是PHP回傳的值";
?>

再寫一個用ajax呼叫的網頁index.html,放在與UniServerZ不同的目錄內:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AJAX 測試01</title>
</head>
<body>
<section id="d4">按下PHP測試</section>
<section id="d5"></section>
</body>
<script src="js/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
$("#d4").click(function(){
$.ajax({
url: "http://localhost/test01.php",
success: function(msg){
alert("成功");
$("#d5").append(msg);
},
error: function(){
alert( "錯誤" );
}
});
});
</script>
</html>

用瀏覽器開啟index.html後測試,果然出現了網域存取錯誤:
XMLHttpRequest cannot load http://localhost/test01.php.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.

Image001  

接著在test01.php加上一行語法,就可以成功存取跨網域的資料
header("Access-Control-Allow-Origin: *");
* 表示所有網站都可以存取;也可以單獨立指定網域,如http://test.com,

完整語法如下:
<?php
header("Access-Control-Allow-Origin: *");
echo "我是PHP回傳的值";
?>

 Image002  

arrow
arrow
    全站熱搜

    keven 發表在 痞客邦 留言(0) 人氣()