简体   繁体   English

打印从Spring MVC Controller发送的String数组,在javascript中仅显示“ toJSON”

[英]Printing an array of String sent from Spring MVC Controller shows only “toJSON” in javascript

I have a list of String (department names) passed from a controller to a JSP page. 我有一个从控制器传递到JSP页面的字符串(部门名称)列表。 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". 但是,当我为每个部门名称发出警报时,我得到了一个字符串“ 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: 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!). 这是我用Remdo的建议解决此问题的方式(谢谢!)。 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)); 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, 因为i不是JSON对象, depArr具有字符串而不是字符串数组,

 mv.addObject("depNameList", depNameList); // depNameList is a type of List<String> 

if you print depNameList in console, output would be like: 如果在控制台中打印depNameList ,则输出将如下所示:

[a, b, c, d] //this is invalid JSON, missing qoutes( " OR ' ) [a,b,c,d] //这是无效的JSON,缺少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: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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