Using XMLHttpRequest
Here is a demo of creating a XMLHttpRequest object and processing the response asynchronously. The server time is captured using a simple handler file and is written onto a label in the page. This refresh happens every second and happens using AJAX
Here is the HTML markup for the page. The body onload calls the function ajaxTime every second. The ajaxTime updates the label with the time at the server.
<body onload="setInterval('ajaxTime();',1000);"> <form id="form1" runat="server"> <div> <asp:Label ID="lblServerTime" runat="server"></asp:Label> </div> </form> </body>The javascript for ajaxTime function is as below. For all browsers, create a new XMLHttpRequest object directly. For IE 6, create the object using the ActiveXObject interface. Handle the onreadystatechange event for processing the response and updating the label. The open method points to the page which will give us the server time.
function ajaxTime() { var xmlHttp; if (window.XMLHttpRequest) { // for all modern browsers xmlHttp = new XMLHttpRequest(); } else { // for IE 6.0 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4) { document.getElementById('lblServerTime').innerText = xmlHttp.responseText; } } xmlHttp.open('GET', 'ServerTime.ashx', true); xmlHttp.send(null); }The code for handler is straight-forward and is shown below:
public void ProcessRequest(HttpContext context) { context.Response.Expires = -1; context.Response.ContentType = "text/plain"; context.Response.Write(DateTime.Now.ToString()); }
Posted by Vijay on 16-Dec-2009 02:26 PM
Category : ASP.NET AJAX
Category : ASP.NET AJAX


