AJAX - The Complete Reference

(avery) #1

122 Part I: Core Ideas


To convert a value into the appropriate x-www-form-urlencoded format, it is suggested
that JavaScript’s encodeURIComponent() method is used. In some older versions of
JavaScript, this method may not be available and then it is necessary to rely on the escape()
method. However, the escape() method will not encode some characters that browsers do,
including @, /, and +. This limitation of escape() is particularly important to note because
it will not encode the plus (+) symbol. You should be quite careful using it for encoding data
to send via Ajax because that nonencoded symbol may wreak havoc in your application: it
will be interpreted as a space on the receiving side. The encodeURIComponent() method
also has certain limitations as it will not encode some characters that browsers do
including ~, !, ., ‘, (, and ),. We should also note that both escape() and
encodeURIComponent() will encode the space character as %20 rather than the + symbol,
which is specified by a strict read of the format. We present here a function to escape the
individual pieces that would be included in an x-www-form-urlencoded request: exactly
as the browser does

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);
/* fix the omissions */
encodedVal = encodedVal.replace(/~/g, '%7E');
encodedVal = encodedVal.replace(/!/g, '%21');
encodedVal = encodedVal.replace(/\(/g, '%28');
encodedVal = encodedVal.replace(/\)/g, '%29');
encodedVal = encodedVal.replace(/'/g, '%27');
}
/* clean up the spaces and return */
return encodedVal.replace(/\%20/g,'+');
}

Interestingly, such details are not handled in most Ajax libraries. Except the possibility
of problems with the + symbol, these omissions are not harmful as most often server-side
environments provide certain latitude in encoding. However, given the emphasis on standards
throughout Web development community, there is no reason to promote such looseness in data
transfer unless you are willing to promote looseness in markup, CSS, or scripting as well.

Extending Standard Encoding


An interesting possible modification to standard URL encoding could be to extend the basic
name-value pair a bit to preserve composite data structures found in JavaScript like arrays
and objects to support their easy submission to a server-side program. This is possible to do
Free download pdf