One of the potential uses of Ajax is to load locale-dependent presentation text on demand. In my article, Using Servlets and JSP to Give Users Control Over Their Presentation Locale, I explained how an Ajax sink could be linked to a browser event such as the
window.onload() to override the default locale.
In this article, I add JSON support for more complex retrievals, such as the contents of a listbox. If you haven't yet read the previous article, you probably should do that before proceeding with this one, as this tutorial contains some references the previous one.
Here is the complete code for this tutorial:
Toggling Between Languages
In providing the ability to override the presentation locale in real time, Ajax can provide the user with a means of choosing his or her preferred language from an HTML control. For instance, in the following example, the mechanism to toggle between the English and French languages is built into a button:
i18n_support.js script, a global variable keeps track of the current locale and provides a handy way to initialize it too. In the button's
onclick() event, we can set the
currentLocale using a ternary operator. The code to set the welcome message and button caption has been moved to the
setLabels() function, as the exact same code gets called for the initializing and updating:
The key for the button caption lookup is
toggle_language. Don't forget to add it to the labels resource bundles!
Here is the
Here is the
Here are the results in the browser:
Handling Complex Data Types
While single string values are easy to send across the network using
GET requests and the Ajax
responseText property, complex data types can be problematic. Consider a
SELECT control. It is made up of multiple Option objects, which themselves contain both a value and text property. This inevitably brings up the idea of using string delimiters and tokens. Not a bad idea, but for transmitting data across a network, it's hard to beat JSON.
What You'll Need
eval function is very fast and simple to use, it poses a security threat as it will execute any code stored in the
myJSONtext variable. Thus, it can unwittingly unleash a malicious script. To defend against this, a JSON parser should be used. A JSON parser will recognize only JSON text, rejecting all scripts. In browsers that provide native JSON support, JSON parsers are also much faster than
json_parse.js. Download it and place it in your scripts folder, where the
protoype.js scripts reside.
On the Java side, you'll also need to include the seven files in the top part of the table on the JSON.org Java page. They are:
These should be placed in a package called
org.json, under your project's source folder.