简体   繁体   中英

Javascript - PHP variable not accessible in external js file

I'm having an issue with an external js file and google maps. The external js file won't recognize an array that I created in the php file. I'm using wordpress, if that matters. In my custom template php file, I am creating a custom query:

    <?php   
        $pages = array(
            'post_type' => 'page',
            'orderby' => 'title',
            'order' => 'ASC',
            'meta_key' => '_wp_page_template',
            'meta_value'=> 'index.php'
        );

        // query results by page template
        $my_query = new WP_Query($pages);

        // array for results of custom query
        $customArray = array();

        if($my_query->have_posts()) : ?>

            <div id="listings">
                <ul>

                <?php while($my_query->have_posts()) : 
                    $my_query->the_post(); 

                    $customArray[] = array(
                    'title' => get_the_title(),
                    'lat' => get_field('latitude'),
                    'long' => get_field('longitude'),
                    'status' => get_field('status'),
                    'industry' => get_field('industry'),
                    'state' => get_field('state')
                    );
                ?>

// output the title of the post into the list
<li><?php the_title(); ?></li>

<?php endwhile; endif; ?>

                </ul>
            </div>

I'm then putting those posts into a google map as markers by converting $customArray into an actual json array called jsonarray.

var mapCanvas = document.getElementById('map-canvas');
    var mapOptions = {
      center: new google.maps.LatLng(40, -95),
      zoom: 4,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    // create the map
    var map = new google.maps.Map(mapCanvas, mapOptions);

    // convert PHP array to json
    var jsonarray = <?php echo json_encode($customArray); ?>;

    // array to hold the markers
    var markers = [];

    // Loop through our array of markers & place each one on the map  
    for( i = 0; i < 4; i++ ) {
        var position = new google.maps.LatLng(jsonarray[i]['lat'], jsonarray[i]['long']);
        var marker = new google.maps.Marker({
            position: position,
            map: map,
            icon: 'http://i.imgur.com/FPiUErC.png',
            title: jsonarray[i]['state']
        });
        markers.push(marker);
    } // end of the for loop

This works fine and the markers show up on the map. However, I want the google map script (above) to be in an external js file. So I removed the map script above and put it into an external file called map.js. I then call map.js in the footer of my php page and set it to document.ready.

The problem with putting the map script into the external js file is that my json array, var jsonarray, is no longer outputting anything. I even tried a basic alert in the map.js file, but it doesn't execute at all:

alert(jsonarray[0]['lat']);

The above alert outputs fine when the map script is in my actual php page, but it no longer outputs anything once the map script is placed in the external js page. It also disables all of the script after it since it isn't recognized. I feel like there has to be a simple reason for this. Do I have to do anything, in particular, to get this to work? It's like the external js file isn't recognizing the php array, customArray, so it's unable to convert it to the json array.

The PHP code in the external JS file will fail because that file is not parsed by php.

Try the same approach but execute this line in the php file, so it will generate the valid value

 <script>
     var jsonarray = <?php echo json_encode($customArray); ?>;
 </script>

After that load your scripts. (it will have access to that variable because was created in the global scope).

The function wp_localize_script() can be used to "make any data available to your script that you can normally only get from the server side of WordPress".

First of all you need to enqueue your script in functions.php (note the handle map-js ):

add_action('wp_enqueue_scripts', function(){
    wp_enqueue_script( 'map-js', get_stylesheet_directory_uri().'/path/to/map.js', array(), false, true );
});

And then after the endif; on your PHP code you can put:

wp_localize_script( 'map-js', 'jsonarray', $customArray );

That passes $customArray to your script in the JavaScript variable jsonarray .


Note: I've set the $in_footer argument of wp_enqueue_script to true to delay the printing of your script, so that wp_localize_script would be called earlier to set the jsonarray variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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