简体   繁体   English

获取访问php中的JavaScript循环值

[英]Get access the JavaScript loop value in php

Here is my code: 这是我的代码:

var marker,i,marker1,k;
for(i=0; i <20; i++)
{
//I want to assign this i variable value in php variable
function addMarker(latLng, map) {
    var marker = new google.maps.Marker({
        position: latLng,
        map: map,
        animation:google.maps.Animation.BOUNCE
    });
 //like as
    var conte='<?php $j="<script>document.write(i);</script>"; 
    ?>';

I want to use that value below here: 我想在下面使用该值:

    var contentvalue= '<div style="color:   #008000;"><strong><b><?php echo  "$b[$j]" ?></b></strong></div>';

     var infowindow = new google.maps.InfoWindow({
      content: contentvalue,

        });
         marker.addListener('click', function() {

    infowindow.open(map, marker);
    });
             return marker[i];
    }   
}

Essentially, you are trying to do this backwards. 本质上,您正在尝试向后执行此操作。 You can use PHP to dynamically build a JavaScript block on the server side but, you cannot use PHP while JavaScript is executing. 您可以使用PHP在服务器端动态构建JavaScript块,但是在执行JavaScript时不能使用PHP。 Since PHP is Server-side and JS is Client-side, you need to decide to go with one of the languages. 由于PHP是服务器端的,而JS是客户端的,因此您需要决定使用其中一种语言。

Also, you shouldn't be defining a function inside of your for loop. 另外,您不应该在for循环内定义函数。 Just define the function outside and call it from within the for loop. 只需在函数外部定义并从for循环中调用即可。

function addMarker(latLng, map) {
    var marker = new google.maps.Marker({
        position: latLng,
        map: map,
        animation:google.maps.Animation.BOUNCE
    });
    return marker;
}
function addInfoBox(contentString) {
    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });
    return infowindow;
}
var i = 0
for(i=0; i < 20; i++)
{
    var contentString='<script>document.write('+i+');</script>'; 
    var marker = addMarker(latLng, map);
    var info = addInfoBox(contentString, marker);
    marker.addListener('click', function() {
        info.open(map, marker);
    });
}

This code is not at all perfect but, I think it gives a general idea of how you should start here. 这段代码并不是很完美,但是我认为它给出了您应该如何开始的总体思路。 You'll have to clean it up and make sure it fits in with your application. 您必须清理它并确保它适合您的应用程序。 I do not see a need for any PHP here as this is all client-side code and Google Maps API does not parse or execute any PHP code. 我看不到这里需要任何PHP,因为这是所有客户端代码,并且Google Maps API不会解析或执行任何PHP代码。

Try : 尝试:

<script>    
    var phparr = <?php echo json_encode($phparr); ?>;

    for (i in phparr){

        alert("hey" + phparr[i]);

    }
</script>

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

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