javascript - <script> 代码中使用的 PHP 变量被添加到 URL

标签 javascript php google-maps

我在 PHP 页面中使用 Google Maps Javascript API,并希望将用户通过 PHP 接收到的值(基本上是用户输入的地址)用于 map JS 代码。我的代码大致设置如下:

<?php $myVar = "new york"; ?>

<script type="text/javascript"
            src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDwKLaKFqCqNs61pylmB8Yqj6I0v1LhE-A">
</script>
<script type="text/javascript">

var latitude, longitude;

var geocoder = new google.maps.Geocoder();
var location = <?php echo json_encode($myVar); ?>;

geocoder.geocode({ "address": location}, function(results, status){
    latitude = results[0].geometry.location.lat();
    longitude = results[0].geometry.location.lng();
});

function initialize() {
    var mapOptions = {
        center: { lat: latitude, lng: longitude},
        zoom: 8
    };
    var map = new google.maps.Map(document.getElementById('map-canvas'),
                                  mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

但是,每次我尝试运行它时,字符串“new york”都会添加到我的 URL 中,如下所示:

http://localhost:8888/quill/shows/the-merchant-of-venice/new%20york

为什么会发生这种情况,我该如何预防?

最佳答案

由于您的代码位于顶层,您的变量location 实际上是window.location,用于设置页面的URL。

将所有 Javascript 代码放在 IIFE 中给它自己的变量范围:

(function() {
    var latitude, longitude;

    var geocoder = new google.maps.Geocoder();
    var location = <?php echo json_encode($myVar); ?>;

    geocoder.geocode({ "address": location}, function(results, status){
        latitude = results[0].geometry.location.lat();
        longitude = results[0].geometry.location.lng();
    });

    function initialize() {
        var mapOptions = {
            center: { lat: latitude, lng: longitude},
            zoom: 8
        };
        var map = new google.maps.Map(document.getElementById('map-canvas'),
                                      mapOptions);
    }
    google.maps.event.addDomListener(window, 'load', initialize);
})();

关于javascript - &lt;script&gt; 代码中使用的 PHP 变量被添加到 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29977097/

相关文章:

Javascript,当按下按钮之间弹出窗口未关闭时,window[] 未定义

php - 如何对wp_query的结果进行排序

php将未知数量的值传递给mysql准备好的语句

php - 语法错误或访问冲突 : 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column

android - 打开 Google Maps for Android Navigation with multiple coordinates as waypoints

javascript - 将数组中的字符串拆分为子字符串

javascript - 切换 + 切换类

javascript - (图形)树结构中的 jQuery sortables

ios - No Such Module Found 在 Podspec 中添加依赖

javascript - AngularJS 范围变量在另一个函数内更改时不会更新