gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:13:07 25 4
gpt4 key购买 nike

我在使用外部 js 文件和 google map 时遇到问题。外部 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

这工作正常并且标记显示在 map 上。但是,我希望谷歌地图脚本(上面)位于外部 js 文件中。所以我删除了上面的 map 脚本并将其放入名为map.js的外部文件中。然后,我在 php 页面的页脚中调用 map.js 并将其设置为 document.ready。

将 map 脚本放入外部js文件中的问题是我的json数组var jsonarray不再输出任何内容。我什至在map.js 文件中尝试了基本警报,但它根本不执行:

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

本地图脚本位于我的实际 php 页面中时,上述警报输出正常,但一旦将 map 脚本放置在外部 js 页面中,它就不再输出任何内容。它还会禁用其后的所有脚本,因为它无法被识别。我觉得这一定有一个简单的原因。我需要做什么特别的事情才能让它发挥作用吗?就像外部js文件无法识别php数组customArray一样,因此无法将其转换为json数组。

最佳答案

外部 JS 文件中的 PHP 代码将失败,因为该文件未被 php 解析。

尝试相同的方法,但在 php 文件中执行此行,因此它将生成有效值

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

之后加载您的脚本。 (它将有权访问该变量,因为是在全局范围内创建的)。

关于Javascript - PHP 变量无法在外部 js 文件中访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30405491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com