PDA

View Full Version : [Ajax] Fetch data from .txt



sysout
04-17-2009, 09:16 AM
I wanna fetch data from 2 files :
- data.txt
- data2.txt
according to the button that I click, but it seems not working.


This is the code :

<html>
<head>
<title>Ajax at work</title>
<script language = "javascript">
var XMLHttpRequestObject = false;
var XMLHttpRequestObject2 = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
XMLHttpRequestObject2 = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHttp");
XMLHttpRequestObject2 = new ActiveXObject("Microsoft.XMLHttp");
}
function getData(dataSource)
{
if(XMLHttpRequestObject) {
var obj = document.getElementById("targetDiv");
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
function getData2(dataSource)
{
if(XMLHttpRequestObject2) {
var obj = document.getElementById("targetDiv");
XMLHttpRequestObject2.open("GET", dataSource);
XMLHttpRequestObject2.onreadystatechange = function()
{
if (XMLHttpRequestObject2.readyState == 4 &&
XMLHttpRequestObject2.status == 200) {
obj.innerHTML = XMLHttpRequestObject2.responseText;
}
}
XMLHttpRequestObject2.send(null);
}
}
</script>
</head>
<body>
<H1>Fetching data with Ajax</H1>
<form>
<input type = "button" value = "Display Message"
onclick = "getData('data.txt')">
<input type = "button" value = "Display Message 2"
onclick = "getData2('data2.txt')">
</form>
<div id="targetDiv">
<p>The fetched data will go here.</p>
</div>
</body>
</html>


thanks for your help :)