前端怎么获取ModelAndView 传的list集合
时间: 2024-02-12 16:07:08 浏览: 21
在前端获取ModelAndView传的list集合,需要将集合封装到JSON格式数据中,然后通过ajax异步请求获取数据。具体步骤如下:
1. 在Controller中将list集合转为JSON格式数据并放入ModelAndView中:
```java
List<String> list = new ArrayList<String>();
// 将list集合转为JSON格式数据
String jsonStr = JSON.toJSONString(list);
ModelAndView mav = new ModelAndView();
mav.addObject("data", jsonStr);
mav.setViewName("viewName");
```
2. 在前端页面中通过ajax异步请求获取数据:
```javascript
$.ajax({
url: "url",
type: "GET",
dataType: "json",
success: function(data) {
var list = JSON.parse(data.data); // 将JSON格式数据转为list集合
// 处理数据
},
error: function() {
alert("请求失败");
}
});
```
通过以上步骤,就可以在前端页面中获取到ModelAndView传的list集合了。
相关问题
modelandview list前端怎么取值
如果您正在使用Spring的ModelAndView类来将数据传递给前端视图,您可以在前端使用JSTL标签库或Thymeleaf模板引擎来获取数据。
对于JSTL标签库,您可以使用<c:forEach>标签遍历列表,例如:
```
<c:forEach items="${list}" var="item">
<p>${item}</p>
</c:forEach>
```
对于Thymeleaf模板引擎,您可以使用th:each指令遍历列表,例如:
```
<div th:each="item : ${list}">
<p th:text="${item}"></p>
</div>
```
其中,${list}是您在ModelAndView类中添加到Model对象的列表数据。
前端从modelandview中拿到返回值
在前端中,可以通过以下步骤从ModelAndView中获取返回值:
1. 在前端页面中使用JSP标签库或者Thymeleaf等模板引擎引入ModelAndView对象。
2. 在JSP页面或者模板引擎中使用EL表达式或者Thymeleaf表达式获取ModelAndView中的返回值。
例如,在JSP页面中可以使用以下语法获取ModelAndView中的属性值:
```
${modelAndView.attributeName}
```
或者在Thymeleaf模板中使用以下语法获取ModelAndView中的属性值:
```
[[${modelAndView.attributeName}]]
```
其中,attributeName为ModelAndView中的属性名。
注意:在使用JSP标签库或者Thymeleaf等模板引擎引入ModelAndView对象时,需要在Controller中将ModelAndView对象添加到Model中,然后返回对应的视图名称,例如:
```
@RequestMapping("/example")
public ModelAndView example() {
ModelAndView mav = new ModelAndView("example");
mav.addObject("attributeName", attributeValue);
return mav;
}
```
在上述代码中,"example"为视图名称,"attributeName"为ModelAndView的属性名,attributeValue为对应的属性值。