Thursday, June 19, 2008

Creating an object out of a string

Something that I had to do in one of my projects was send a HTTP request from javascript to a Servlet and get some information back. But, what's better to hold data than an Object?
So I decided to make the servlet send an object back as a response to that javascript request. Here is what I did.

Javascript sends AJAX request
Servlet receives request
Servlet sends an object as a string (eg: {property1: "hello", property2: "World", property3: "!"})
Javascript reads the response and interprets it as a string

In order to turn that encapsulated object in a string to a real javascript object you'll need to use the eval() function and append parenthesis to both sides of the string.

//Since this entry is not to teach you how to do AJAX requests I'm just going to assign a string to a variable and call it "ajaxRequest"
var ajaxResponse = "{property1: "hello", property2: "World", property3: "!"}";

//Notice the parethesis before and after the string that has the object
var myObject = eval( "("+ajaxResponse+")");

alert(myObject.property1 + " " + myObject.property2 + " " + myObject.property3);

Pretty cool uh?