简体   繁体   中英

Pass an attribute to an external javascript file in thymeleaf- passed as empty string

From my controller I add an Object to my model, which I can access within the Html. example

 redir.addFlashAttribute("userId",userId);
 return modelAndView;

Within the HTML if I access the userId

 <input type="hidden" id="userId" th:value="${userId}" /> - 

I can see the result. I have an external JS file, that has a function that takes as an input parameter userId. How do I read the userId directly to the JS file ? Cuz if I do it like this :

var userId=$("userId").val(); 

the userId doesn't take the value. It shows an empty string. How do I fix this ?

您必须在 html #userId为 id 使用选择器

var userId=$("#userId").val();

jQuery's val method looks at the value attribute, so it ignores th:value . You need to use the .attr method, eg $('#userId).attr('th-value') .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM