Neero Neero - 4 months ago 64
jQuery Question

Access Spring MVC model object within jquery

This is how I return my model object from the controller.

model.addObject("gameSchList", gameSchList);
return model;


I got my response as a JSON output because I used Spring JAXB implementation.
This is the output I got from my Spring controller.

{
"gameSchList":
[
{
"team":
[
{
"alias": "A",
"logo": "A_LOGO"
},
{
"alias": "B",
"logo": "B_LOGO"
}
],
"cName": "AZ",
"id": "58",
"type": "game",
"channel": "713",
"time": "Sun 13:00PM",
"status": "pregame"
}
]


}

Now I want to access this gameSchList within document ready function. This is an external js file which I added to my homepage.



Now within that gameinfo.js, I created a ready function and tried to access gameSchList using the below code. I need this requirement within js file without using jstl.

$(document).ready(function(){
var list = ${gameSchList};
$.each(list, function( index, value ) {
alert( index + ": " + value );
});
});


When I call this controller it redirects to my homepage and executes this particular gameinfo.js, but it gives me this error:


SyntaxError: missing ; before statement


I tried it several ways, but no luck for me.

var list = ${model.gameSchList};
var list = "${model.gameSchList}";

Answer

Here is one solution, that you can try. In your jsp declare the below which gets evaluated on server side (make sure its in jsp and not on external js file).

<script type="text/javascript">
 var responseObject= ${gameSchList};
</script>

Now you have access to responseObject on js and you can use it on your document.ready function. Hope this helps.