本帖最後由 lolmuta 於 2015-4-27 17:42 編輯
寫一個xmlhttp請求,但是一直出現錯誤, No 'Access-Control-Allow-Origin' header is present
[執行環境]:chrome 版本 42.0.2311.90 m
[目標]:作一個按鈕,點擊後,會產生一個xmlhttp請求,url是本網站的首頁(http://jsgears.com), 當得到正確的回應時,就將整個document改寫成
xmlhttp的responseText.
[錯誤與網頁資訊]:一開始出現這個錯誤時,以為加上header Access-Control-Allow-Origin:*就好了…但是仍然錯誤…其實,是因為查到太多看都看不懂的東西,只是取其中的關鍵來用= =,這裡想順便請教一下,是否有好的書可推薦的…
[代碼]:<!DOCTYPE html>
<html>
<script>
function aaaa(){
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","http://jsgears.com",true);
xmlhttp.setRequestHeader("Access-Control-Allow-Origin","*");
xmlhttp.send();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
//document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
var responsetxt=xmlhttp.responseText;
document.write(responsetxt);
}
}
}
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=BIG5">
<title>Insert title here</title>
<button type="button" onclick="aaaa()">Test</button>
</head>
<body>
</body>
</html> [詳細錯誤]:
XMLHttpRequest cannot load http://jsgears.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. |