[英]Calling method on JavaScript variable passed in using 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(
您不能混合使用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>
使用此代碼,我能夠獲取傳入的元素並放入列表中並遍歷該列表。
/*<![CDATA[*/
//list of locations passed from controller to view using thymeleaf
var locations = [];
/*[# th:each="n : ${locations}"]*/
locations.push("[(${n})]");
/*[/]*/
/ ]]> /
//loop through user locations
for(var i = 0; i < locations.length; i++){
axios.get(' https://maps.googleapis.com/maps/api/geocode/json ',{參數:{
address:locations[i],
key:'AIzaSyC0_mpWB_nOm_gsjWwbgD_2EXYsnYTD6Jg'
}
})
//using response from api to add markers to map
.then(function(response){
console.log(response)
var lat = response.data.results[0].geometry.location.lat;
var lng = response.data.results[0].geometry.location.lng;
addMarker({lat:lat,lng:lng});
})
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.