<html>
<!DOCTYPE >
<html>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<body>
<a href="file/ajax.txt">Load AJAX File</a>
<br /><br />
<a href="file/ajax.txt">Load AJAX HTML</a>
<script src="js/main.js" ></script>
</body>
</html>
</html>
<script>
(function() {
var link = document.getElementsByTagName("a")[0];
link.onClick = function() {
// XHR Object
var xhr = new XMLHttpRequest();
// Handle the On Read State Change Event
// xnr. readyState property values
// 0 = ininitialized
// 1 = Loading
// 2 = Loaded
// 3 = Interactive
// 4 = Complete
xhr.onreadystatechange = function() {
if ((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)) {
var body = document.getElementByTagName("body")[0];
var p = document.createElement("p");
var pText = document.createTextNode(xhr.responseText);
p.appendChild(pText);
body.appendChild(p);
}
};
// Open request
xhr.open("GET", "files/ajax.text", true);
// Send Request to Server
xhr.send(null);
return false;
};
})();
</script>
When I click the link it goes to the page instead of GETing the info and appending it.
(function() {
var link = document.getElementsByTagName("a")[0];
link.onClick = function() {
// XHR Object
var xhr = new XMLHttpRequest();
// Handle the On Read State Change Event
// xnr. readyState property values
// 0 = ininitialized
// 1 = Loading
// 2 = Loaded
// 3 = Interactive
// 4 = Complete
xhr.onreadystatechange = function() {
if ((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)) {
var body = document.getElementByTagName("body")[0];
var p = document.createElement("p");
var pText = document.createTextNode(xhr.responseText);
p.appendChild(pText);
body.appendChild(p);
}
};
// Open request
xhr.open("GET", "files/ajax.txt", true);
// Send Request to Server
xhr.send(null);
return false;
};
})();
$.ajax({
url : "file/ajax.txt",
dataType: "text",
success : ajaxCallback
});
function ajaxCallback(result, status, xhr) {
var body = document.getElementByTagName("body")[0];
var p = document.createElement("p");
var pText = document.createTextNode(result.responseText);
p.appendChild(pText);
body.appendChild(p);
};
<a href="file/ajax.txt" onclick="return false;">Load AJAX File</a>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function makeCall()
{
$.ajax({
url: "AjaxTextFile.txt",
dataType: "text",
success: ajaxCallback
});
}
function ajaxCallback(result, status, xhr)
{
var body = document.getElementsByTagName("body")[0];
var p = document.createElement("p");
var pText = document.createTextNode(result);
p.appendChild(pText);
body.appendChild(p);
}
</script>
</head>
<body>
<a href="file/ajax.txt" onclick="makeCall(); return false;">Load AJAX File</a>
<br /><br />
<a href="file/ajax.txt">Load AJAX HTML</a>
</body>
</html>