如何在JavaScript中获取Spring MVC控制器模型键值? [英] How to get spring mvc controller model key value inside javascript?
问题描述
我正在使用Spring MVC控制器.我在控制器内部放置一些值,让模型内部说一个字符串.现在,我想检索该值,或者只说在javascript中打印该值.我该怎么做? 这是我的控制器类.我正在添加电影"作为关键.现在,我想在Java脚本中显示电影的名称(不是在JSP中.而是在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";
}
}
这是我的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>
推荐答案
使用此:
var movie_name = "${movie}";
代替:
var movie_name = ${movie};
使用${movie}
时,该值将不带引号放在页面上.由于我猜这是一个字符串,因此Javascript要求字符串用引号引起来.
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.
如果您检查了浏览器的控制台,则可能会看到类似Unexpected identifier
或___ is not defined
的错误.
If you checked your browser's console, you probably would've seen an error like Unexpected identifier
or ___ is not defined
.
这篇关于如何在JavaScript中获取Spring MVC控制器模型键值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!