I am working with the Play framework (2.4) for Java. I want to pass a JSONObject to a javascript used inside one of the Play view templates.
On the Java side I prepare the JSONObject, like so:
(Keep in mind that this is a test vehicle.)
public static Result showBusinesses(){
List<Item> list = new ArrayList<Item>();
Item r = new Item();
r.id = "23234";
r.name = "Joes hardware";
Item s = new Item();
s.id = "23254";
s.name = "Martys collision";
list.add(r);
list.add(s);
return ok(views.html.wheel.render(getJSONObject(list)));
}
public static JSONObject getJSONObject(List<Item> list){
JSONObject jsonObject = new JSONObject();
try{
for (int i = 0; i < list.size(); i++) {
jsonObject.put(list.get(i).id, list.get(i).name);
}
}catch (JSONException e) {
}
return jsonObject;
}
In my Play template, I accept the JSONObject parameter:
@(item : org.json.JSONObject)
@import helper._
@import helper.twitterBootstrap._
@import play.api.libs.json.Json
...
So far, so good.
Until I attempt to use the object in my javascript:
If I place my object, @item, anywhere in the template besides inside the javascript, I get this: {"23254":"Martys Pancakes","23234":"Joes place"}; which looks like a properly formed var to me.
I am inserting the JSONObject into the javascript like this:
<script type="text/javascript">
businesses = @item;
and I expect that to translate like this:
businesses = {
"23332" : "Joe's hardware",
"56755" : "Marty's collision"
};
And yet the object does not behave as expected. I suspect that I am not passing the parameter to the javascript in the correct way.
Can anyone enlighten me? Thanks.
var businesses = ...?