AJAX - The Complete Reference

(avery) #1

PART II


Chapter 9: Site and Application Architecture with Ajax 431


Traditionally, this might have been done by reading the response value and then adding
some DOM code to the callback function and generating the replaced content like so:

/* get response packet */
var ratingResponse = AjaxTCR.data.decodeJSON(response.responseText);

/* find insertion point */
var responseOutput = $id("responseOutput");
/* make heading */
var responseHeading = document.createElement("h3");
var responseHeadingText = document.createTextNode("Thanks for voting! ");
responseHeading.appendChild(responseHeadingText);
responseOutput.appendChild(responseHeading);

/* show results */
var para1 = document.createElement("p");
var rawText1 = "Your rating: " + ratingResponse.rating;
var text1 = document.createTextNode(rawText1);
para1.appendChild(text1);
responseOutput.appendChild(para1);

var para2 = document.createElement("p");
var rawText2 = "Average rating: " + ratingResponse.average;
var text2 = document.createTextNode(rawText2);
para2.appendChild(text2);
responseOutput.appendChild(para2);

var para3 = document.createElement("p");
var rawText3 = "Total votes: " + ratingResponse.votes;
var text3 = document.createTextNode(rawText3);
para1.appendChild(text3);
responseOutput.appendChild(para3);

This solution is quite long and leaves many opportunities for error, so you might instead
simply set the innerHTML property of some target <div> to a string with particular tokens
replaced like so:

var ratingResponse = AjaxTCR.data.decodeJSON(response.responseText);

var ratingWidget = $id("ratingWidget");
var responseOutput = "<h3>Thanks for voting!</h3><p>Your rating: "+
ratingResponse.rating + ".<br />";
responseOutput += "Average rating: "+ratingResponse.average+".<br />";
responseOutput += "Total votes: "+ratingResponse.votes+".<br />";
responseOutput +="</p>";
ratingWidget.innerHTML = responseOutput;

Now this starts to look more like a template in the style of an MVC pattern, but it is
still buried within the code. You can see why it would be simpler just to generate the result
server side and slap the response into the page on the client-side with one line of code.
Free download pdf