Monday, July 21, 2008

Most simple XMLHttpRequest example.

For the ones need to get a quick start here goes a very simple XMLHttpRequest example with pure javascript. Note that this example works with the Firefox. For the Internet Explorer "xmlhttp = new XMLHttpRequest();" line should be changed with "xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");" although this usage varies with the Internet Explorer version.

At the server side you need a text.txt file which contains a partial html document such as:

<p> hello </p>

The code:

<html>

<head>

<script language="javascript" type="text/javascript">

function back_ajax()
{
if (xmlhttp.readyState == 4)
{
var o = document.getElementById('o');
o.innerHTML = xmlhttp.responseText;
}
}

function call_ajax()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.txt", true);
xmlhttp.onreadystatechange = back_ajax;
xmlhttp.send(null);
}

</script>

</head>

<body>

<form name="f">
<input name="in"/>
<input type="button" onClick="call_ajax()"/>
</form>

<div id="o">
<ul>
<li> test 1 </li>
<li> test 2 </li>
</ul>
</div>

</body>

</html>

1 comment:

Anonymous said...

Perfect, thanks.

Label Cloud