How to do HTTP requests from within the browser using JavaScript.
Mozilla supports the native XMLHttpRequest object and IE supports an ActiveX Object called Msxml2.XMLHTTP. Luckily both hese objects work the same!
This is the basis for AJAX style server interaction.
There are text files on the web server sample1.txt, sample2.txt and sample3.txt, clicking the buttons below will make JavaScript make an HTTP call to the server and output the contents of the file into the textarea box below.
debug
<script type="text/javascript">
<!--
var debugCounter = 0;
function debugMsg(msg) {
debugCounter++;
var t = document.createTextNode("\n" + debugCounter + ": " + msg);
var br = document.createElement("br");
var debug = document.getElementById("debug");
debug.appendChild(t);
debug.appendChild(br);
}
function getDataViaHTTP(req)
{
document.forms[0].out.value = "";
if ( typeof XMLHttpRequest == "object" ) {
var xhr = new XMLHttpRequest();
}
if ( typeof ActiveXObject == "object" || typeof ActiveXObject == "function") {
var xhr = new ActiveXObject("Msxml2.XMLHTTP")
}
if ( typeof xhr != "object" ) {
debugMsg("Could no get an XML HTTP object (" + typeof xhr + " " + typeof ActiveXObject + ")");
return;
}
debugMsg("getting " + req);
xhr.open("GET", req, false);
xhr.send(null);
resp = xhr.responseText;
if ( resp.length < 0 ) {
debugMsg("Response too short");
return;
}
var rawLines = resp.split("\n");
if ( typeof rawLines != "object" ) {
debugMsg("Bad Response (it may be empty)");
return;
}
debugMsg("got " + rawLines.length + " lines writing to textarea");
document.forms[0].out.value = resp;
}
// -->
</script>
<form action="index.html" method="get">
<p>
<input type="button" onclick="getDataViaHTTP('sample1.txt');" value="Get sample1.txt" />
<input type="button" onclick="getDataViaHTTP('sample2.txt');" value="Get sample2.txt" />
<input type="button" onclick="getDataViaHTTP('sample3.txt');" value="Get sample3.txt" />
</p>
<p><textarea cols="60" rows="5" name="out">Some text</textarea></p>
</form>
<b>debug</b><br /><span id="debug"></span>