我正在尝试实现 Ajax 调用,并且遇到了以下代码:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Let AJAX change this text.</p>
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "www.google.com", true);
xhttp.send();
}
</script>
</body>
</html>
我尝试访问 URl,但最终出现错误,提示“XHR 无法加载”。 我知道这和CORS有关。我浏览了几页,但发现很难理解这个问题。有人可以解释并解决这个问题吗?会有帮助的
最佳答案
Google 不允许跨域访问其搜索引擎。您的方法似乎没问题,只是您尝试访问的网址不允许您的域名。
使用本地计算机上托管的文件进行尝试
关于javascript - 如何使用CORS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33278032/