簡體   English   中英

Javascript-無法在外部js文件中訪問PHP變量

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

我在使用外部js文件和Google Maps時遇到問題。 外部js文件無法識別我在php文件中創建的數組。 如果有問題,我正在使用wordpress。 在我的自定義模板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>

然后,我通過將$ 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

這樣可以正常工作,並且標記會顯示在地圖上。 但是,我希望上面的google map腳本位於外部js文件中。 因此,我刪除了上面的地圖腳本,並將其放入名為map.js的外部文件中。 然后,我在PHP頁面的頁腳中調用map.js並將其設置為document.ready。

將地圖腳本放入外部js文件的問題是我的json數組var jsonarray不再輸出任何內容。 我什至在map.js文件中嘗試了基本警報,但它根本沒有執行:

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

當地圖腳本位於我的實際php頁面中時,上面的警報輸出很好,但是一旦將地圖腳本放置在外部js頁面中,它將不再輸出任何內容。 它還會禁用所有腳本,因為該腳本無法識別。 我覺得必須有一個簡單的原因。 為了使它正常工作,我是否需要做任何事情? 就像外部js文件無法識別php數組customArray一樣,因此無法將其轉換為json數組。

外部JS文件中的PHP代碼將失敗,因為該文件未被php解析。

嘗試相同的方法,但是在php文件中執行此行,因此它將生成有效值

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

之后,加載您的腳本。 (因為它是在全局范圍內創建的,因此可以訪問該變量)。

wp_localize_script()函數可用於“使腳本通常只能從WordPress的服務器端獲得的任何數據都可用於腳本”。

首先,您需要將腳本放入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 );
});

然后在endif;之后 在您的PHP代碼上,您可以輸入:

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

這會將$customArray傳遞給JavaScript變量jsonarray中的腳本。


注:我已經設置了$in_footer的說法wp_enqueue_scripttrue耽誤你的腳本的打印,使wp_localize_script會更早稱為設置jsonarray變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM