<html> <body> <form id="TestForm"> <p></p> Try this: <input id="TestButton" type="button" onclick="ServerRequest();" value="Test Me"/> <p></p> <input id="TestBox" type="text" NAME="TestBox"/> </form> </body></html><script language="javascript"> function ServerRequest( ){ var term = "This is a test"; var url = "TestHandler.axd"; if (window.XMLHttpRequest){ // branch for native XMLHttpRequest object request = new XMLHttpRequest(); request.onreadystatechange = processRequestChange; //false = the script waits for the request to be sent and for a response to arrive from the server request.open("POST", url, false); request.send(term); } else if (window.ActiveXObject){ // branch for IE/Windows ActiveX version request = new ActiveXObject("Microsoft.XMLHTTP"); if (request){ request.onreadystatechange = processRequestChange; //false = the script waits for the request to be sent and for a response to arrive from the server request.open("POST", url, false); request.send(term); } } document.getElementById("TestBox").value = request.responseText; } function processRequestChange(){ // only if request shows "loaded" if (request.readyState == 4){ // only if "OK" if (request.status == 200) { // Any processing you want goes here. } else { alert("There was a problem retrieving the XML data:\n" + request.statusText); } } }</script>
Your project will then need an IHttpHandler created to accept and process HTTP requests.
using System;using System.IO;using System.Xml;using System.Web;using System.Web.SessionState;namespace MyTestRequest{ public class TestHandler : IHttpHandler, IReadOnlySessionState { public void ProcessRequest(HttpContext context) { // Ingest the http request StreamReader reader = new StreamReader(context.Request.InputStream); string searchTerm = context.Server.UrlDecode( reader.ReadToEnd() ); // Do your processing here... // Set the context response's properties (optional) context.Response.ContentEncoding = System.Text.Encoding.UTF8; context.Response.ContentType = "text/xml"; // Send the response context.Response.Write( searchTerm ); } public bool IsReusable { get { return false; } } }}
Finally, the web.config will need the following settings supplied in the system.web section.
That is it for this example. We are able to do some client processing, send an HttpRequest to the server and receive a response while not refreshing the web browser. The functionality in this example is trivial, but the possibilities seem endless. ASP.NET 2.0 will make this example for ASP.NET 1.x easier with built-in script callbacks.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2010 MuellerDesigns.net
Sign In