AJAX - The Complete Reference

(avery) #1

Chapter 2: Pre-Ajax JavaScript Communications Techniques 25


PART I


html.appendChild(body);
}

/* make form */
var ifrForm = ifrDoc.createElement("FORM");
ifrForm.action = url;
ifrForm.method = "post";
ifrDoc.body.appendChild(ifrForm);
/* add fields for each value in payload */
for (var key in payload)
{
var ifrText = ifrDoc.createElement("INPUT");
ifrText.type = "text";
ifrText.name = key;
ifrText.value = payload[key];
ifrForm.appendChild(ifrText);
}
return ifrForm;
}

Now in the rating function, to make life easy, encode the payload into an object notation
which you will come to know in Chapter 4 as JSON (JavaScript Object Notation). With this
format, it is simple to perform a loop over the properties of the object creating the fields to send.

var transport = "iframe";
var payload = {"rating":ratingVal, "comment":encodeValue(comment),
"transport":transport};

To fully exercise the use of the POST method, the ongoing rating example has been
modified to also allow a comment value entered by the user in a <teaxtarea> field along
with the simple numeric rating. Given that there could be values that may be problematic to
transmit, it is necessary to escape them. The obvious choice might be to use JavaScript’s
escape() method or even better the encodeURIComponent()if it is available. However,
neither get things quite correct, as spaces should be translated not to %20, but to the “+”
character and they avoid addressing certain encodings. Fortunately, such details don’t hurt
much in practice, but to aim for precision, it is straightforward to employ a simple wrapper
function to escape the values properly.

function encodeValue(val)
{
var encodedVal;
if (!encodeURIComponent)
{
encodedVal = escape(val);
/* fix the omissions */
encodedVal = encodedVal.replace(/@/g,"%40");
encodedVal = encodedVal.replace(/\//g,"%2F");
encodedVal = encodedVal.replace(/\+/g,"%2B");
}
else
{
encodedVal = encodeURIComponent(val);
Free download pdf