各位大大好!小弟,有買一本書叫Javascript第一次學就上手,讀到Ajax的範例,自己重新手打過後,出現CORS ERROR,我該如何解決呢?
ERROR照片訊息如下:
ERROR訊息如下:
Access to XMLHttpRequest at 'file:///C:/Users/toudf/OneDrive/%E6%A1%8C%E9%9D%A2/%E8%87%AA%E5%B7%B1%E7%B7%B4%E7%BF%92/Javascript/ajax/books.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.
json.html:13
GET file:///C:/Users/toudf/OneDrive/%E6%A1%8C%E9%9D%A2/%E8%87%AA%E5%B7%B1%E7%B7%B4%E7%BF%92/Javascript/ajax/books.json net::ERR_FAILED
html程式碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="utility.js"></script>
<script>
var XHR = null;
function startRequest() {
XHR = createXMLHttpRequest();
XHR.open("GET", "books.json", true);
XHR.onreadystatechange = handleStateChange;
XHR.send(null);
}
function handleStateChange() {
if (XHR.readyState == 4) {
if (XHR.status == 200) {
data = JSON.parse(XHR.responseText);
var newContent = '';
for (var i = 0; i < data.length; i++) {
newContent += '<p>' + data[i].title + '</p>';
}
document.getElementById("span1").innerHTML = newContent;
}
else
window.alert("無法顯示書名!");
}
}
</script>
</head>
<body>
<form id="form1">
<input id="button1" type="button" value="顯示書名" onclick="startRequest()">
<br><br><span id="span1"></span>
</form>
</body>
</html>
utility.js程式碼如下:
function createXMLHttpRequest()
{
try //其它非IE的瀏覽器
{
var XHR = new XMLHttpRequest();
}
catch(e1)
{
try //IE6+瀏覽器
{
var XHR = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e2)
{
try //IE5瀏覽器
{
var XHR = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e3) //不支援Ajax
{
XHR = false;
}
}
}
return XHR;
}
book.json程式碼如下:
[
{
"title": "新趨勢計算機概論",
"price": 500,
"description": "針對大專院校計算機概論課程所設計"
},
{
"title": "新趨勢網路概論",
"price": 520,
"description": "針對大專院校網路概論課程所設計"
},
{
"title": "網頁程式設計",
"price": 490,
"description": "涵蓋網頁程式設計相關技術"
}
]
是,這不是CORS 的問題
你是用 file:///C:/Users/toudf/OneDrive/%E6%A1%8C%E9%9D%A2/%E8%87%AA%E5%B7%B1%E7%B7%B4%E7%BF%92/Javascript/ajax/books.json 在跑你的綱頁的, 應該要用真正的 server 來跑.
找找看 Apache, XAMPP, MAMP 之類的.
https://www.apachefriends.org/jp/index.html
之後再用 http://localhost/%E6%A1%8C%E9%9D%A2/%E8%87%AA%E5%B7%B1%E7%B7%B4%E7%BF%92/Javascript/ajax/books.json
來跑得話應該就沒問題了.