AJAX: Display Contents
To output the contents from a file, we can use "alert()". The
syntax is:
alert(msg);
But "alert() can only display the contents in the alert popup window.
How to print the contents to the screen? We use:
document.getElementById
Or:
document.all
For example:
document.getElementById('message');
Or:
document.all('message');
'message' is an id for a HTML tag. We can assign an id to a HTML tag:
<div id="message"></div>
<p id="message"></p>
<h1 id="message"></h1>
<input type="text" id="message">
...
Please note that there are two sorts of tags: one is regular HTML tags,
like <p>, <h1>, <div>, <b>, etc; another is element
tag of HTML form, like <input> and <textarea>.
To print contents inside regular HTML tags, we use "innerHTML".
The syntax is:
document.all('message').innerHTML=msg;
document.getElementById('message').innerHTML=msg;
To display contents inside an element tag of a HTML form, you must use
"value". The syntax is:
document.all('message').value=msg;
document.getElementById('message').value=msg;
Let's modify the above example as below:
<html><head>
<script type="text/javascript" language="javascript">
function requestHttp(url,posTag){
var httpRequest;
if(window.XMLHttpRequest){// Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
if(httpRequest.overrideMimeType){
httpRequest.overrideMimeType('text/xml');
}
}else if(window.ActiveXObject){ // IE
try{
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e){
try{
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){}
}
}
getFile(httpRequest,url,posTag);
}
function getFile(httpRequest,url,posTag){
if(!httpRequest){
alert('Error - Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function(){
showContents(httpRequest,posTag);
}
httpRequest.open('GET', url, true);
httpRequest.send('');
}
function showContents(httpRequest,posTag){
if(httpRequest.readyState == 4){
if(httpRequest.status == 200){
var msg=httpRequest.responseText;
//alert(msg);
document.all('message').innerHTML=msg;
document.all('inputText').value=msg;
}else{
alert('Error');
}
}
}
</script>
</head><body>
<span
style="cursor: pointer; text-decoration: underline"
onclick="requestHttp('file1.txt','message')">
Show contents
</span>
<div id="message"></div>
<form>
<input type="text" id="inputText" value="">
<input type="button" id="Button2" value="Submit"
onclick="requestHttp('file1.txt','message')" >
</form>
</body></html>
When you click the link "Show contents", you will see the contents
displaying inside the tags '<div id="message"></div>';
If you click the button "Submit", you will see the contents
showing in the text input box. |