Combine Ajax and JSON to Transmit Complex Presentation Data | 2 | WebReference

Combine Ajax and JSON to Transmit Complex Presentation Data | 2


Combine Ajax and JSON to Transmit Complex Presentation Data [con't]

Populating a ComboBox

To see how JSON could be used to populate a SELECT control, we'll create a combobox for selecting the page language. In addition to the English and French Canada locales, we'll include a default one that will select US English. Here are the contents of the file:

To avoid including multiple values on one line, each list item is distinguished by dot notation (much like Java packages): language (DOT) locale (DOT) property. (e.g. language.en_CA.value).

Also add the same properties to the en_CA and fr_CA properties files.

In the i18nSupportTestPage.jsp file, include the following code directly below the language toggle button:

Prototype JSON Support

To retrieve the text from the servlet for each SELECT Option, we need to pass the Option code values to the server from the setLabels() JavaScript function. This can be done using Prototype's useful Array.toJSON() method. All we need to do is convert the Options collection into an iterable Array and extract the value properties from them. Worded in that way, it sounds easy. In fact, it would take a fair amount of JavaScript code without the Prototype Framework.

Using Prototype shortcuts and functions, it can be done in one line! First, the dollar sign $() function returns the SELECT element. We can apply the getElementsByTagName() function on it to return the Options collection. From there, the Option collection is converted to a proper Array using the $A() shortcut function. Finally, the pluck() function returns the value properties from the Array. The toJSON() function is applied to the resulting aKeys array and appended to the baseURL to be sent to the Ajax call. The key property has also been pluralized to reflect that there are many keys now:

The change_locale Action

When the servlet receives an action of "change_locale", it fetches the keys parameter and passes it to the JSONArray object's constructor. In a for loop, we can retrieve each key using the JSONArray.get() function. Since all of the language keys follow the same naming format, we just need to substitute the locale code to retrieve the value from the language bundle. Each key/value pair is stored in its own JSON object and appended to the outValues JSONArray. The toString() function converts the object back into string format for transmission over the network:

Parsing the JSON String in the Ajax Callback Function

Now you can see why we needed to import the json_parse.js script. While Prototype has an evalJSON() method that also solves the security threat associated with using eval() on JSON-encoded strings, the json_parse() function has an extra reviver parameter that can be used to convert string values into other objects. It iterates over every key/value pair so that some type of conversion can be performed on the value.

We don't need to return anything because we don't need to store the resulting objects. Rather, what we want to do is replace each Option's text property with the contents of the associated JSON property as defined by the locale code. Here is the JSONArray string that is returned from the French language bundle:

It is important that the keys are also returned so that we don't rely on Option ordering as any sorting would alter item ordering.

Again, Prototype makes obtaining a reference to the SELECT's Option collection a fairly painless process. The dollar sign $() function returns the listbox and the getElementsBySelector() function fetches the Option that matches the key. It uses CSS selectors to determine which elements to look for. In our case we are inserting the locale code, giving us something like "[value=en_CA]". We have to use the first() function on the results because getElementsBySelector() returns an Array. We can assume that the Array contains exactly one item because the listbox Option values are expected to be unique:

Again, here is the complete code download for this tutorial:


  • Have a suggestion for an article topic? Do you have a product or service that you'd like reviewed? Email it to Rob .

    Rob Gravelle combined his love of programming and music to become a software guru and accomplished guitar player. He created systems that are used by Canada Border Services, CSIS and other Intelligence-related organizations. As a software consultant, Rob has developed Web applications for many businesses and recently created a MooTools version of PHPFreechat for ViziMetrics. Musically, Rob recently embarked on a solo music career, after playing with Ivory Knight since 2000. That band was rated as one Canada's top bands by Brave Words magazine (issue #92) and released two CDs. Rob's latest release is called "The Rabbit of Seville". Loosely based on Rossini's The Barber of Seville overture, Rob's amazing rendition includes a full orchestra and numerous guitar tracks. It is sold on his site as a high bitrate MP3 for only $0.99 cents! Rob is available for short-term software projects and recording session work. to inquire, but note that, due to the volume of emails received, he cannot respond to every email. Potential jobs and praise receive highest priority!

    Original: September 1, 2010