尝试使用AJAX将数据从JS发送到PHP

时间:2016-06-01 07:52:56

标签: javascript php jquery ajax google-maps

我正在尝试将一些数据从JavaScript发送到PHP,但似乎我做错了。我正在使用反向地理编码来获取谷歌地图上特定标记的位置名称,这很好用。但是,我需要PHP端的特定数据。

这就是我的脚本的样子, var markerLocation 是我想要遇到的变量(js / map_article.js):

// Reverse geocoding
function geocodeLatLng(geocoder, map, infowindow) 
{   
    result.forEach(function(entry) {
        var latlng = {lat: parseFloat(entry.lat), lng: parseFloat(entry.lng)};
        geocoder.geocode({'location': latlng}, function(results, status)
        {
            if (status === google.maps.GeocoderStatus.OK)
            {
                if (results[1])
                {
                    var marker = new google.maps.Marker({
                            position: latlng,
                            map: map
                        });
                    infowindow.setContent(results[1].formatted_address);
                    infowindow.open(map, marker);

                    var markerLocation = results[1].formatted_address;

                    // Send the adress back to php
                    $.ajax({
                        type: "POST",
                        url: 'article.php',
                        data: {markerLocation : markerLocation},
                        success: function(data)
                        {
                            alert("success!");
                        }
                    });

                } 
                else 
                {
                    window.alert('No results found');
                }
            }
            else
            {
                window.alert('Geocoder failed due to: ' + status);
            }
        });

    });
}

这就是PHP(article.php)的样子:

<?php
    $id = $_GET['id'];
    $sql = "SELECT * FROM blog WHERE id=$id";
    $result = db_select($sql);
?>

<script type="text/javascript">
    // pass PHP variable declared above to JavaScript variable
    var result = <?php echo json_encode($result) ?>;
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script type="text/javascript" src="js/map_article.js"></script>

<body>

<?php

    // Is the AJAX-data coming across?
    if(isset($_POST['markerLocation']))
    {
        echo "<p>".$_POST['markerLocation']."</p>"; 
    } 
    else
    {
        echo "<p>It did not work..</p>";
    }

?>

</body>
</html>

警告信息“成功!”确实显示,但变量$ _POST ['markerLocation']仍未定义。我哪里出错了?

0 个答案:

没有答案