使用Thymeleaf传入的JavaScript变量的调用方法

时间:2018-09-04 03:37:09

标签: javascript thymeleaf

我正在使用Thymeleaf将包含控制器地址的ArrayList对象传递给JavaScript视图。我试图遍历此列表,并向Google Maps geocding API发送请求。我的问题是在循环中.length或.size()在此变量上不起作用。我确实知道对象正在传递给视图,但是我不知道为什么其余的代码没有运行。 这是我实际的JavaScript代码。

    <script th:inline="javascript">


       /*<![CDATA[*/
//list of locations passed from controller to view using thymeleaf
var locations = [[${locations}]];
// .length not working on variable
console.log(locations.size());
var size = locations.length;
//loop through user locations .length and .size() not working
for(var i=0; i < locations.length; i++){
    console.log(locations[i])
    //make call to api using location

这是我检查代码时看到的内容

       /*<![CDATA[*/
//list of locations passed from controller to view using thymeleaf
var locations = ["12 Main St bonne terre mo 63628"," 100 division st bonne terre mo 63628","4345 fyler ave st louis mo 63116","12 Main St bonne terre mo 63628"];
// .length method not running on variable
console.log(locations.size());
var size = locations.length;
//loop through user locations .length method not working
for(var i=0; i < locations.length; i++){
    console.log(locations[i])
    //make call to api to get activity.location coordinates

$。ajax({     类型:“ GET”,     网址:“ https://maps.googleapis.com/maps/api/geocode/json?address=” +

我可以看到我的地址列表正在传入,但是不知道为什么我无法获取循环列表的长度。

我尝试过

 for(var i=0; i < [[${locations.size()}]]; i++){
    console.log([[${locations[i]}]])

但是我未被识别,也没有从列表中拉出任何东西。 这是页面检查。

//loop through user locations .length and .size() not working
for(var i=0; i < 4; i++){
    console.log(

documentation

2 个答案:

答案 0 :(得分:0)

您不能混合使用Javascript和Thymeleaf变量。例如,在以下代码中:

for(var i=0; i < [[${locations.size()}]]; i++){
    console.log([[${locations[i]}]])

您正在JavaScript中定义i,并希望Thymeleaf知道i在下一行代码console.log([[${locations[i]}]])中的含义。 i未定义,因此什么都不会打印出来。由于您现在已经有了位置列表:

var locations = [[${locations}]];

从那时起,您应该只处理javascript变量。该代码将起作用:

<script th:inline="javascript">
  /*<![CDATA[*/
  var locations = /*[[${locations}]]*/ [];

  for(var i=0; i < locations.length; i++){
    console.log(locations[i]);
  }

  /*]]>*/
</script>

答案 1 :(得分:0)

使用此代码,我能够获取传入的元素并放入列表中并遍历列表。

+---------+--------+-------+--------+-------+--------+-------+
| Account | Badge1 | Name1 | Badge2 | Name2 | Badge3 | Name3 |
+---------+--------+-------+--------+-------+--------+-------+
|     123 |    456 | Bob   |    789 | John  |    654 | Carl  |
+---------+--------+-------+--------+-------+--------+-------+

/ ]]> /

           /*<![CDATA[*/
//list of locations passed from controller to view using thymeleaf






var locations = [];

/*[# th:each="n : ${locations}"]*/

    locations.push("[(${n})]");
    /*[/]*/

axios.get('https://maps.googleapis.com/maps/api/geocode/json',{         参数:{

//loop through user locations 
for(var i = 0; i < locations.length; i++){
相关问题