這是我第一次使用AJAX,我似乎無法弄清楚爲什麼.txt文件不會加載?而是去只顯示文本的新頁面),即:在同一個頁面沒有加載:第一個AJAX項目...(不會加載文本文件內聯)
我的index.html頁面:
<html>
<head>
<meta charset="utf-8">
<title>Learning Ajax</title>
</head>
<body>
<!-- my first AJAX script -->
<h1>Learning Ajax</h1>
<a href="files/ajax.txt">Load Text Files</a>
<script src="js/main.js"></script>
</body>
</html>
這裏是我main.js腳本:
var message = "Test";
(function() {
var link = document.getElementsByTagName("a")[0];
link.onClick = function(){
var xhr = new XMLHttpRequest();
//handle the 'onreadystatechange" event
//0 = un-initialized
//1 = loading
//2 = loaded (sent to server)
//3 = interactive (server is responding)
//4 = complete (request finished)
xhr.readystatechange = function(){
if((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)){
xhr.responseText;
var body = document.getElementsByTagName("body")[0];
var p = document.createElement("p");
var pText = document.createTextNode(xhr.responseText);
p.appendChild(pText);
body.appendChild(p);
};
//open the request
xhr.open("GET", "files/ajax.txt", true);
//send the request
xhr.send(null);
return false;
};
};
})();
alert(message);
我ajax.txt文件
..我只是有一些隨機的純文本:這是要加載的Ajax文本。
我不是本地運行這一點,但使用WAMP的Web服務器通過本地主機..
我缺少什麼?或在這裏俯瞰?
教程鏈接:tutsplus.com/lesson/the-simplest-ajax-script
嘗試將您的內容更改爲{'這是要加載的Ajax文本'}並將文件名改爲ajax.json –