我想獲得一個AJAX示例工作,但我無法讓它工作。你能在XAMPP上運行嗎?AJAX不在本地主機上工作
我有三個文件,message.txt,index.html,ajaxtest.js。當你點擊超鏈接時,它會彈出message.txt的內容。 (所有文件都在同一個目錄)
的index.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);
}
}
}
當您點擊鏈接時,它的行爲完全一樣,並帶我進入一個新的頁面,其中包含message.txt文件的內容 – Colin747
控制檯中出現的錯誤是什麼? – koenpeters
你的問題不清楚。你有錯誤信息嗎?什麼是預期的行爲/得到的行爲? –