[英]How to pass an external JSON file into a javascript variable that can be accessible anywhere
[英]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_script
至true
耽误你的脚本的打印,使wp_localize_script
会更早称为设置jsonarray
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.