jQuery releases Javascript pain

I have a html page to display xml files from the same server. The reasons I didn’t use the server side script includes

  1. ruby needs rails, but I don’t want to create an application for this single page. I tried to run ruby as cgi, no success.
  2. maggiePie can make php eaiser, but I think it’s still kind of overkill for this simple use.

Then I turned to client-side javascript. At first I use this function to load xml file:

function loadXMLtoDIV(file, div_name) {

var xmlDoc = null;

var moz = (typeof document.implementation != ‘undefined’)
&& (typeof document.implementation.createDocument != ‘undefined’);
var ie = (typeof window.ActiveXObject != ‘undefined’);

if (moz) {

xmlDoc = document.implementation.createDocument(“”, “”, null);
xmlDoc.load(file);
xmlDoc.onload = function() { readXML(xmlDoc, div_name); };

} else if (ie) {

xmlDoc = new ActiveXObject(“Microsoft.XMLDOM”);
xmlDoc.async = false;
while(xmlDoc.readyState != 4) {};
xmlDoc.load(file);
readXML(xmlDoc, div_name);
}

}

It worked very well, and I like it until I tried use jQuery:

function XmlOnLoad( xmlData, divId ){

// Get the first 2 items
var jItems = jQuery(‘item:lt(2)’, xmlData);

var jDiv = $( divId );

// reset.
jDiv.html(”);

jItems.each(
function( ){
jDiv.append( $(this).find(‘pubDate’).text() + ‘ : ‘ +$(this).find(‘title’).eq(0).text() +'<br/>’);
}
);
}
function GetXMLData(file, divId){
$.get(file,{},
function(xmlData, status) {
XmlOnLoad(xmlData, divId);
} );

}

And another benefit from jQuery is, I can move those ‘behavior’ from the presentation part. This jQuery ‘onload’ function is to add an universal click event to all the itemlist class div. By doing this my html elements look much neater.

$(function(){

$(“div.itemlist”).each(

function(n){
var current = this;

$(“<a href=”>See latest items … </a>”).click(  function(event){
GetXMLData(   “#”+current.id); return false;}  ).appendTo($(this));
}
);

})

One thing I still don’t understand, if I tried to load too many xml file into the page elements, some xml files just missed. jQuery still doesn’t fix this problem. But coverting from loading to ajax using jQuery is so easy, so I didn’t spent too much time on it at all.

For those TDD fans, you want to look in this QUnit intro.

Advertisements

One thought on “jQuery releases Javascript pain

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s