How do you access a model attribute in jquery?
Asked Answered
P

3

13

I'm adding an object to my ModelAndView in spring and forwarding to my jsp view. I need to access that object in my jquery. Is this possible without first putting the value in a hidden field? How is it done?

Paine answered 16/2, 2011 at 19:50 Comment(0)
A
29
<script type="text/javascript">
   var modelAttributeValue = '${modelAttribute}';
</script>

This will resolve the model attribute added by model.addAttribute("modelAttribute", value)

Associate answered 16/2, 2011 at 20:2 Comment(2)
hmm. this does not work when the jquery function is a part of a js file that is imported into the UI templateBonaparte
How can I set a modelAttribute property?Geese
L
3

probably, you can save the model attribute in a hidden field and access it onload as below.

$(document).ready(function(){
  var modelAttr = $("#modelAttr").val();
  alert(modelAttr);
}

input type="hidden" id="modelAttr" name="modelAttr" value="${modelAttribute}"/>

Add c:out around the ${modelAttribute} in the jsp.

Ludmilla answered 1/6, 2011 at 9:29 Comment(1)
Only this solution works in my case (Spring+Thymeleaf+JS). Passing a String is no problem, but how can I pass a list or an array of Strings?Syllabary
R
1

In java controller,

model.addAttribute("key", "value");

inside jQuery,

let name = [[${key}]];
console.log("modelAttributeValue: ", name)
Rousseau answered 31/10, 2022 at 23:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.