简体   繁体   English

如何通过使用for循环在js中获取ModelAndView对象?

[英]How could I get ModelAndView object in js by using for loop?

I want to ask, how could I get ModelAndView object's value in js by using for loop? 我想问,如何通过for循环在js中获取ModelAndView对象的值?

In controller, I wrote this: 在控制器中,我这样写:

@RequestMapping(value="SearchCourse.html", method=RequestMethod.GET)
public ModelAndView searchCourse() {
    ModelAndView model = new ModelAndView("/student/SearchCourse");
    model.addObject("schoolList", schoolService.listSchool());
    return model;
}

In js, if I wrote: 在js中,如果我写了:

${
    schoolList.get(0).getSchoolname()
}

Then, I can get the result. 然后,我可以获得结果。

However, if I wrote a for loop: 但是,如果我写了一个for循环:

var schoolList = new Array();
for(var i = 0; i < "${schoolList.size()}"; i++) {
    alert("${schoolList.get("+i+").getSchoolname()}"); //error
}

Then, I will get an error. 然后,我会得到一个错误。 I know I can't get write code like the above because i misuse the syntax. 我知道我无法获得上述代码,因为我滥用了语法。 But, how can I get the schoolList in js by using ModelAndView? 但是,如何使用ModelAndView在js中获取schoolList?

The first expression is not JavaScript, it is jstl expression. 第一个表达式不是JavaScript,而是jstl表达式。 If you want access to the model in JavaScript you either need to assign values to javascript variables or return JSON objects to your requests. 如果要使用JavaScript访问模型,则需要为javascript变量分配值或将JSON对象返回到您的请求。 To assign values to javascript array, you should do something like this: 要将值分配给javascript数组,您应该执行以下操作:

<script>
 var schoolList=new Array();
  <c:forEach items="schoolList" var="school">
      schoolList[]=${school.schoolname};
   </c:forEach>

</script>

Notice, that there is a mix of javascript and jstl in this code. 注意,此代码中混合了javascript和jstl。 This is a sample code, there might be errors. 这是示例代码,可能存在错误。

Check the answers to the questions below which were similar to yours. 检查以下与您相似的问题的答案。

How to transfer java array to javaScript array using jsp? 如何使用jsp将java数组转换为javaScript数组?

How to pass array from java to javascript 如何将数组从Java传递到JavaScript

Converting a Java ArrayList of strings to a JavaScript array 将字符串的Java ArrayList转换为JavaScript数组

Thanks @jny ! 谢谢@jny! I have figured it out by myself. 我自己弄清楚了。 We can simply use the code below to get the list and iterate the list. 我们可以简单地使用下面的代码来获取列表并迭代列表。

<script>
var schoolList=${schoolList}
for(var i=0;i<schoolList.length;i++) {
  alert(schoolList[i].schoolname);
}
</script>

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

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