Streamlining my Javascript some more...

by James 11/14/2007 6:23:00 AM
I've been working on updating the MyUCR project at work. I'm always amazed at how much I learn, looking at my code from a year ago gives me shudders, compared to what I know now. For instance, here's a snippet of an Ajax call from last year:
var url = "ajax.aspx?getSingleMsg="+msgID + "&msgTypeID=" + getMessageType();
var xhrReq = xhrRequest("text");
xhrReq.open("GET", url, true);
xhrReq.onreadystatechange = function()
{
if(xhrReq.readyState == 4 && xhrReq.status == 200)
{
DisplaySingleMsg(xhrReq.responseText, getMessageType())
};
}
sendRequest(xhrReq);

 

Yikes! That's a heck of a lot of lines to write and maintain. I love using jQuery, but hadn't really gotten into its Ajax events. I wish I had done so earlier. Now the same code looks like this:

var url = "ajax.aspx?getSingleMsg="+msgID + "&msgTypeID=" + getMessageType();
$.get(url, function(xhr){DisplaySingleMsg(xhr, getMessageType());});

Sweet!

James

Latest crazy song in my head Les Boukakes - Bledi - L'Alawi