Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get spring mvc controller model key value inside javascript?

I am using a spring mvc controller. Inside controller i am putting some value lets say string inside model. Now i would like to retrive that value or lets just say print that value inside a javascript. How do i do it? Here is my controller class. I am adding "movie" as key. Now i want to display that name of the movie inside java script (Not inside JSP. However Inside JavaScript)

@Controller
@RequestMapping("/movie")
public class MovieController {

    @RequestMapping(value="/{name}", method = RequestMethod.GET)
    public String getMovie(@PathVariable String name, ModelMap model) {

        model.addAttribute("movie", name);
        return "list";

    }

}

here is my JSP

<html>
<head>
//I want to print movie name inside java script not inside jSP body tag.
<script type="text/javascript">
var movie_name = ${movie};
alert("movies name"+ movie_name);
</script>
</head>
<body>
    <h3>Movie Name : ${movie}</h3>//When i print here its working fine. 
</body>
</html>
like image 271
Dheeraj Varne Avatar asked Apr 25 '13 05:04

Dheeraj Varne


2 Answers

Use this:

var movie_name = "${movie}";

instead of:

var movie_name = ${movie};

When using ${movie}, the value gets placed on the page without quotes. Since I'm guessing it's a string, Javascript requires strings be surrounded by quotes.

If you checked your browser's console, you probably would've seen an error like Unexpected identifier or ___ is not defined.

like image 90
Ian Avatar answered Oct 16 '22 23:10

Ian


Try this...

If you had added the object into the model as:

model.addAttribute("someObject", new Login("uname","pass"))

Then you get the properties of the model object as

var user_name = ${someObject.uname}; // This is assuming that the Login class has getter as getUname();
var user_pass = ${someObject.pass};
like image 42
Arun Avatar answered Oct 17 '22 01:10

Arun