这是我的第一个 Ajax 程序,我无法修复代码,因为我不确定问题出在哪里。
使用调试器时的错误(我无法解释)是, XMLHttpRequest 无法加载 http://localhost/function.txt .请求的资源上不存在“Access-Control-Allow-Origin” header 。因此不允许访问 Origin 'null'。
function calling()
{
var x;
if (window.XMLHttpRequest) {
x = new XMLHttpRequest();
} else {
x = new ActiveXObject("Microsoft.XMLHTTP");
}
x.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200)
{
document.getElementById("block").innerHTML = this.responseText;
}
};
x.open("GET", "http://localhost/function.txt",true);
x.send();
}
函数.txt
<html>
<head></head>
<body>
<h2>Ajax is working</h2>
</body>
</html>
最佳答案
您的 js 是否与您的 function.txt 位于同一位置?
有关 CORS 的更多信息,请查看此链接:https://www.html5rocks.com/en/tutorials/cors/
更新: 这对我有用,我认为您的 Apache 设置可能有问题...
function calling()
{
var xhr = new XMLHttpRequest(),
method = "GET",
url = "function.txt";
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
alert(xhr.responseText);
}
};
xhr.send();
}
calling();
关于javascript - Ajax 中的 URL open(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43140323/