jQuery 如何在javascript中获取spring mvc控制器模型键值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16206754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:41:13  来源:igfitidea点击:

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

javascriptspringjspjqueryspring-mvc

提问by Dheeraj Varne

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)

我正在使用 spring mvc 控制器。在控制器内部,我在模型中放置了一些值让我们说字符串。现在我想检索该值,或者只是说在 javascript 中打印该值。我该怎么做?这是我的控制器类。我正在添加“电影”作为关键。现在我想在 java 脚本中显示电影的名称(不在 JSP 中。但是在 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

这是我的 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>

回答by Ian

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.

使用时${movie},该值被放置在没有引号的页面上。因为我猜它是一个字符串,Javascript 要求字符串用引号括起来。

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

如果您检查浏览器的控制台,您可能会看到类似Unexpected identifier或的错误___ is not defined

回答by Arun

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};