我遇到外部js文件和谷歌地图的问题。外部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数组。
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
此工作正常,标记显示在地图上。但是,我希望谷歌地图脚本(上面)位于外部js文件中。所以我删除了上面的地图脚本并将其放入名为map.js的外部文件中。然后我在我的php页面的页脚中调用map.js并将其设置为document.ready。
将地图脚本放入外部js文件的问题是我的json数组var jsonarray不再输出任何内容。我甚至在map.js文件中尝试了一个基本警报,但它根本没有执行:
alert(jsonarray[0]['lat']);
当地图脚本在我的实际php页面中时,上面的警报输出正常,但是一旦将地图脚本放在外部js页面中它就不再输出任何内容。它也会禁用它之后的所有脚本,因为它不被识别。我觉得这有一个简单的原因。特别是,我必须做任何事情才能让它发挥作用吗?就像外部js文件没有识别php数组customArray一样,所以它无法将它转换为json数组。
答案 0 :(得分:3)
外部JS文件中的PHP代码将失败,因为该文件未被php解析。
尝试相同的方法但在php文件中执行此行,因此它将生成有效值
.row
之后加载脚本。 (它可以访问该变量,因为它是在全局范围内创建的。)
答案 1 :(得分:0)
函数wp_localize_script()
可以用来为您的脚本提供任何通常只能从WordPress服务器端获取的数据&#34;。
首先,您需要将您的脚本排入functions.php
(请注意句柄map-js
):
add_action('wp_enqueue_scripts', function(){
wp_enqueue_script( 'map-js', get_stylesheet_directory_uri().'/path/to/map.js', array(), false, true );
});
然后在您的PHP代码endif;
之后,您可以输入:
wp_localize_script( 'map-js', 'jsonarray', $customArray );
将$customArray
传递给JavaScript变量jsonarray
中的脚本。
注意:我已将$in_footer
的{{1}}参数设置为wp_enqueue_script
以延迟打印脚本,以便{{1之前会调用以设置true
变量。