Javascript also supports the HTTP request. With the HTTP request, we can write scripts that can GET or POST data. It is a way of communicating with web servers i.e.
Client-> server
or
server->client
In this part1, we will discover how to initiate the HTTP class or object and then open a file.
Initiating the HTTP class or object
The first step is to create an instance of the class or object.
//Initiating the class for browsers that dont support the microsoft ActiveXObject i.e safari, opera, chrome...
if(!window.ActiveXObject)
{
http= new XMLHttpRequest();
}
//For those that support ActiveXObject i.e microsoft Internet Explorer.
else{
http= new ActiveXObject("Microsoft.XMLHTTP");
}
After initializing the class or objects as done above, we can now open/access any file on the same domain using the open() method and view the content using the responseText
Note that trying to open google.com would generate an error since google is not on your web domain.
So lets put it all up together.
We open a file named test.txt
The file contains the text: "hello you!".
And then we finally alert its content.
//a variable "http"
var http= null;
//Initiating the class for browsers that dont support the microsoft ActiveXObject i.e safari, opera, chrome...
if(!window.ActiveXObject)
{
http= new XMLHttpRequest();
}
//For those that support ActiveXObject i.e microsoft Internet Explorer.
else{
http= new ActiveXObject("Microsoft.XMLHTTP");
}
//open a file named test.txt
//Note that the file must be in our domain.
http.open('GET','test.txt',false);
http.send(null);
//alert the content.
alert(http.responseText);
Its as easy as that. The result will be :
hello you!
The content from the test.txt file is extracted and printed on our page. It can be any file i.e .html, .css...
This is a basic use and introduction to using HTTP request in javascript. More methods and techniques will be dealt with in later parts of this series.
To rap it all up, lets create a function named openDOC. Our little function will allow us to open files in our domain when called as thus: openDOC("test.txt");
function openDOC(url){
//a variable "http"
var http= null;
//Initiating the class for browsers that dont support the microsoft ActiveXObject i.e safari, opera, chrome...
if(!window.ActiveXObject)
{
http= new XMLHttpRequest();
}
//For those that support ActiveXObject i.e microsoft Internet Explorer.
else{
http= new ActiveXObject("Microsoft.XMLHTTP");
}
//open a file passed as an arguement in the openDOC function.
http.open('GET',url,false);
http.send(null);
//alert the content.
alert(http.responseText);
}
Then to run it:
openDOC("test.txt");
No comments:
Post a Comment