简体   繁体   English

Javascript-无法在外部js文件中访问PHP变量

[英]Javascript - PHP variable not accessible in external js file

I'm having an issue with an external js file and google maps. 我在使用外部js文件和Google Maps时遇到问题。 The external js file won't recognize an array that I created in the php file. 外部js文件无法识别我在php文件中创建的数组。 I'm using wordpress, if that matters. 如果有问题,我正在使用wordpress。 In my custom template php file, I am creating a custom query: 在我的自定义模板php文件中,我正在创建一个自定义查询:

    <?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. 然后,我通过将$ customArray转换为称为jsonarray的实际json数组,将这些帖子作为标记添加到Google地图中。

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. 但是,我希望上面的google map脚本位于外部js文件中。 So I removed the map script above and put it into an external file called map.js. 因此,我删除了上面的地图脚本,并将其放入名为map.js的外部文件中。 I then call map.js in the footer of my php page and set it to document.ready. 然后,我在PHP页面的页脚中调用map.js并将其设置为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. 将地图脚本放入外部js文件的问题是我的json数组var jsonarray不再输出任何内容。 I even tried a basic alert in the map.js file, but it doesn't execute at all: 我什至在map.js文件中尝试了基本警报,但它根本没有执行:

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. 当地图脚本位于我的实际php页面中时,上面的警报输出很好,但是一旦将地图脚本放置在外部js页面中,它将不再输出任何内容。 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. 就像外部js文件无法识别php数组customArray一样,因此无法将其转换为json数组。

The PHP code in the external JS file will fail because that file is not parsed by php. 外部JS文件中的PHP代码将失败,因为该文件未被php解析。

Try the same approach but execute this line in the php file, so it will generate the valid value 尝试相同的方法,但是在php文件中执行此行,因此它将生成有效值

 <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". wp_localize_script()函数可用于“使脚本通常只能从WordPress的服务器端获得的任何数据都可用于脚本”。

First of all you need to enqueue your script in functions.php (note the handle map-js ): 首先,您需要将脚本放入functions.php (请注意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; 然后在endif;之后 on your PHP code you can put: 在您的PHP代码上,您可以输入:

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

That passes $customArray to your script in the JavaScript variable jsonarray . 这会将$customArray传递给JavaScript变量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. 注:我已经设置了$in_footer的说法wp_enqueue_scripttrue耽误你的脚本的打印,使wp_localize_script会更早称为设置jsonarray变量。

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

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