【发布时间】:2016-01-20 06:21:47
【问题描述】:
我正在尝试使用 XMLHttpRequest 对象在 JavaScript 中创建一个示例。我制作了一个html文件如下:
<!DOCTYPE HTML>
<html>
<head>
<title>
AJAX simple example
</title>
</head>
<body>
<div id="mainContent">
<h1>This is an AJAX example</h1>
</div>
<script src="script.js"></script>
</body>
</html>`
我的脚本是这样的:
//simple AJAX example:
var myRequest;
if (window.XMLHttpRequest) {
myRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
myRequest = new ActuveXObject("Microsoft.XMLHTTP");
}
myRequst.onreadystatechange = function(){
console.log(myRequest.readyState);
if(myRequest.readyState === 4){
var p = document.createElement("p");
var text = document.createTextNode(myRequest.responseText);
p.appendChild(text);
document.getElementById("mainContent").appendChild(p);
}
};
myRequest.open("GET", "source.txt", true);
myRequest.send(null);
我在 chrome 中打开 html 文件时不断收到错误,我在控制台中收到以下错误:
XMLHttpRequest 无法加载文件:.../ajaxRequestExample/source.txt。跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https、chrome-extension-resource。
【问题讨论】:
-
从
http://而不是file:///运行它。您也可以使用 chrome 标志,但对于更实际的测试,强烈建议使用简单的 HTTP。如果你有 python,有一个内置的,你可以用一个命令行启动。 -
您应该使用一些服务器来通过
ajax从那里获取任何内容。即使您进行一些实验,这也是一种很好的做法。 -
我猜@dandavis 试图建议您从 localhost 运行文件。另外,请使用 micro ajax 而不是 code.google.com/p/microajax
-
与问题无关,但除非您支持 Internet Explorer ActiveXObject 分支...
-
@MikeMcCaughan:它应该如图所示工作,具体取决于区域,但让我们保持真实:谁在乎?编辑:实际上不,它不会如图所示工作,ie 分支需要首先出现,因为 IE7 在
file:///s 上有一个“Broken”xmlHttpReuest
标签: javascript ajax google-chrome