I have a list of String (department names) passed from a controller to a JSP page. I need to get each individual name and use it as the key to a map (the map value will be a list of employees for that department). However, when I do alert for each department name, I got a string "toJSON". How do I get each name in a readable string? Some department name contain special character like apostrophes, slash. Many Thanks!
Controller:
@RequestMapping(value = "/getDepartment", method = { RequestMethod.POST, RequestMethod.GET })
public ModelAndView getDepartment()
{
ModelAndView mv = new ModelAndView();
mv.addObject("depNameList", depNameList); // depNameList is a type of List<String>
mv.setViewName("displayDepartment");
return mv;
}
JSP:
$(document).ready(function()
{
var depArr = "${depNameList}";
alert(depArr); // this printed a list of department names
for ( var i in depArr)
{
alert("i=" + i); // this printed "i=toJSON"
alert("i=" + JSON.stringfy(i)); // this didn't get invoked.
}
});
Here is how I solved the issue with Remdo's suggestion (Thank you!). I didn't change on the controller side.
var depArr =[]
<c:forEach items="${depNameList}" var="depName">
depArr.push("${depName}");
</c:forEach>
alert("i=" + JSON.stringfy(i)); // this didn't get invoked.
because i
is not a JSON object, depArr
has a string not array of string,
mv.addObject("depNameList", depNameList); // depNameList is a type of List<String>
if you print depNameList
in console, output would be like:
[a, b, c, d] //this is invalid JSON, missing qoutes( "
OR '
)
Also, If you run with above statement compiler will throw a error like:
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', ']'
Solution :
Change:
var depArr = "${depNameList}";
To:
var depArr =[]
<c:forEach items="${depNameList}" var="depName">
depArr.push(\"${depName}\");
</c:forEach>
See Also:
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.