【问题标题】:SpringFramework Iterate through ArrayList in JavascriptSpringFramework 在 Javascript 中遍历 ArrayList
【发布时间】:2021-07-06 18:21:07
【问题描述】:

当我使用 Google 地图在地图上显示对象时,我需要访问我的对象的 ArrayList,该对象是在 Java(Spring 框架)中创建的。

控制器代码

@GetMapping("/")
    public String home(Model model){
        List<LocationStats> allStats = covidDataService.getAllStats();
        int totalCases=allStats.stream().mapToInt(stat->stat.getLatestTotalCases()).sum();
        int totalNewCases=allStats.stream().mapToInt(stat->stat.getDiffFromPreviousDay()).sum();
        model.addAttribute("locationStats", allStats); // I want to iterate this list
        model.addAttribute("totalReportedCases",totalCases);
        model.addAttribute("totalNewCases",totalNewCases);
        model.addAttribute("test",25000);

        return "home";
    }

home.html 中的 Javascript 代码

for (let stat of [[${locationStats}]]){
        console.log(stat.locationStats);
        }

我得到了错误: (index):1701 Uncaught SyntaxError: Unexpected token '{'

排队

 for (let stat of [LocationStats{state=&#39;&#39;, country=&#39;Afghanistan&#39;, latestTotalCases=57144}, LocationStats{state=&#39;&#39;, country=&#39;Albania&#39;, latestTotalCases=128155}, LocationStats{state=&#39;&#39;, country=&#39;Algeria&#39;, 
.....
LocationStats{state=&#39;&#39;, country=&#39;Zambia&#39;, latestTotalCases=89918}, LocationStats{state=&#39;&#39;, country=&#39;Zimbabwe&#39;, latestTotalCases=37273}]){
        console.log(stat.locationStats);
        }

您能帮我解决这个错误吗?

【问题讨论】:

  • 这不是有效的语法。将响应保存在变量中,然后对其进行迭代。

标签: javascript java list spring-boot


【解决方案1】:

可以解决这个问题。从 Java 中的 List 手动构建 JSON。在 Javascript 中,唯一需要的是将“替换为”符号。不知何故,在发送到 html 的过程中,它放置了 " 符号。现在一切正常。

package com.hsrw.covid.controllers;

import com.google.gson.Gson;
import com.hsrw.covid.models.LocationStats;
import com.hsrw.covid.services.DataService;
import net.minidev.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

@Controller
public class HomeController {

    @Autowired
    DataService covidDataService;

    @GetMapping("/")
    public String home(Model model){
        List<LocationStats> allStats = covidDataService.getAllStats();
        int totalCases=allStats.stream().mapToInt(stat->stat.getLatestTotalCases()).sum();
        int totalNewCases=allStats.stream().mapToInt(stat->stat.getDiffFromPreviousDay()).sum();

        model.addAttribute("locationStats", allStats);
        model.addAttribute("totalReportedCases",totalCases);
        model.addAttribute("totalNewCases",totalNewCases);

        StringBuilder builder = new StringBuilder();

        builder.append("[");
        for( LocationStats stat:allStats){
            builder.append("{");
            builder.append("\"state\":\""+stat.getState()+"\",");
            builder.append("\"country\":\""+stat.getCountry()+"\",");
            builder.append("\"lat\":"+stat.getLat()+",");
            builder.append("\"long\":"+stat.getLong()+",");

            builder.append("\"ltc\":"+stat.getLatestTotalCases()+"");

            builder.append("},");
        }
        builder.setLength(builder.length() - 1);
        builder.append("]");
        //System.out.println(builder.toString());
        //System.out.println(JSONArray.toJSONString(allStats));
        System.out.println(builder.toString());
        //model.addAttribute("json", JSONArray.toJSONString(allStats));//builder.toString());
        model.addAttribute("json", builder.toString());
        model.addAttribute("max_stat",covidDataService.getMax_stat());

        return "home";
    }
}


<script>
    // LOCATION IN LATITUDE AND LONGITUDE.
    var center = new google.maps.LatLng(19.0822507, 72.8812041);

    function initialize() {
        // MAP ATTRIBUTES.
        var mapAttr = {
            center: center,
            zoom: 10,
            mapTypeId: google.maps.MapTypeId.TERRAIN
        };

        // THE MAP TO DISPLAY.
        var map = new google.maps.Map(document.getElementById("mapContainer"), mapAttr);
var max_stat=[[${max_stat}]];
var s="[[${json}]]".replaceAll("&quot;","\"");
         //console.log(s);
        var obj=JSON.parse(s);

       for (var i = 0; i < obj.length; i++){
  var obj2 = obj[i];
  var lat=0;
  var long=0;
  var ltc=0;
  for (var key in obj2){
  if(key=="lat")
    lat=obj2[key];
    if(key=="long")
    long=obj2[key];
   if(key=="ltc")
    ltc=obj2[key];
  }
  if(lat!=0){
  console.log(lat);
  console.log(long);
  console.log(ltc);
  console.log(max_stat);
  console.log(750000*ltc/max_stat);

  var dot = new google.maps.LatLng(lat, long);
    var circle = new google.maps.Circle({
            center: dot,
            map: map,
            radius: 1000000*ltc/max_stat,          // IN METERS.
            fillColor: '#FF6600',
            fillOpacity: 0.3,
            strokeColor: "#FFF",
            strokeWeight: 0         // DON'T SHOW CIRCLE BORDER.
        });
  }
 // break;
}
infoWindow = new google.maps.InfoWindow();
  const locationButton = document.createElement("button");
  locationButton.textContent = "Pan to Current Location";
  locationButton.classList.add("custom-map-control-button");
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton);
  locationButton.addEventListener("click", () => {
    // Try HTML5 geolocation.
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          };
          infoWindow.setPosition(pos);
          infoWindow.setContent("Location found.");
          infoWindow.open(map);
          map.setCenter(pos);
        },
        () => {
          handleLocationError(true, infoWindow, map.getCenter());
        }
      );
    } else {
      // Browser doesn't support Geolocation
      handleLocationError(false, infoWindow, map.getCenter());
    }
  });
    }

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
  infoWindow.setPosition(pos);
  infoWindow.setContent(
    browserHasGeolocation
      ? "Error: The Geolocation service failed."
      : "Error: Your browser doesn't support geolocation."
  );
  infoWindow.open(map);
}

    google.maps.event.addDomListener(window, 'load', initialize);
</script>

【讨论】:

    猜你喜欢
    • 2013-12-26
    • 2015-11-28
    • 1970-01-01
    • 2019-01-25
    • 2014-10-21
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多