我正在尝试使 AJAX 示例正常工作,但无法正常工作。你能在 XAMPP 上运行它吗?
我有三个文件,message.txt、index.html、ajaxtest.js。当您单击超链接时,它应该会弹出一个带有 message.txt 内容的弹出窗口。(所有文件都在同一个目录中)
索引.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title> Using XMLHttpRequest</title>
<script type="text/javascript" src="ajaxtest.js"></script>
</head>
<body>
<p>
<a href="message.txt" onclick="grabFile(this.href); return false;">
Click here
</a>
</p>
</body>
</html>
ajaxtest.js
function getHTTPObject() {
var xhr = false;
if (window.XMLHttpRequest) { //see if a XMLHttpRequest exists
xhr = new XMLHttpRequest(); //if it exists change "xhr" to a new instance of the object
}
else if (window.ActiveXObject) { //see if ActiveX exists (for IE)
try { //Allows newer versions of IE to use the newer ActiveX object
xhr = new ActiveXObject("Msxml2.AMLHTTP"); //if it exists change "xhr" to a new instance of the object
}
catch(e) { //catches an error and resets "xhr" to false
try { //Allows older versions of IE to fall back onto the older version using "try...catch"
xhr = new ActiveXObject("Microsoft.XMLHTTP"); //if it exists change "xhr" to a new instance of the object
}
catch(e) {
xhr = false;
}
}
}
return xhr;
}
function grabFile(file) {
var request = getHTTPObject();
if (request) {
request.onreadystatechange = function() {
displayResponse(request);
};
request.open("GET", file, true);
request.send(null);
}
}
function displayResponse(request) {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 304) {
alert(request.responseText);
}
}
}