HTML and CSS Reference
In-Depth Information
18.4.1 Using Ajax to Retrieve Text From a File
In Example 18.6, we use Ajax to request and return ASCII text from a file and display
the response results in a div container. For a more sophisticated example of an Ajax pro-
gram using a text file, see http://www.dynamicdrive.com/dynamicindex2/ajaxticker.htm.
This Ajax ticker program adds the ability to periodically refetch the contents of an exter-
nal file. All source code is provided.
At http://www.JavaScriptkit.com/dhtmltutors/ajaxticker/index.shtml you can find another
excellent tutorial on how to combine RSS, Ajax, and JavaScript to create a live RSS ticker.
Example 18.6 provides an Ajax program to get text from a file. The CSS file (Example
18.9) and the JavaScript file (Example 18.8) to create the request object are external file.
The text file is shown in Example 18.7.
The Ajax Program—“ajaxGetText.htm”
EXAMPLE 18.6
<html>
<head><title>Reading From a Text File with Ajax</title>
<link rel="stylesheet" type="text/css" href="ajaxTextFile.css" />
<script type="text/javascript" src="ajaxCreateRequest.js">
</script>
<script type="text/javascript">
function getText(url) {
1
var ajaxRequest=createRequest() ; * Cross-browser check;
Get a new XMLHttpRequest object */
if( ajaxRequest != false){ /* If we got back a request
object create callback function to check state of
the request */
2
ajaxRequest.onreadystatechange = function() {
3
if ( ajaxRequest.readyState == 4 ){
if ( ajaxRequest.status == 200 ||
ajaxRequest.status==0){
4
document.getElementById('data').innerHTML=
ajaxRequest.responseText ;
}
else {
alert('There was a problem with the request.');
}
}
} // End callback function
}
5
ajaxRequest.open('GET', url, true); // Initialize the
// object
ajaxRequest.setRequestHeader('If-Modified-Since',
'Sat, 03 Jan 2010 00:00:00GMT');
// Deal with the cache
6
ajaxRequest.send(null) ; // Send the request
Continues
 
 
Search WWH ::




Custom Search