在php中$ _POST请求后执行JavaScript代码

时间:2013-12-04 07:47:46

标签: javascript php jquery geocoding

我想在带有地理编码的地图上放置一个标记。我得到了一个有效的代码:

$(document).ready(function(){
    $('#submit').click(function(){
        var address = document.getElementById("address").value + ", CH";
        geocoder.geocode(
            {'address': address},
        function(results, status){          
            if(status == google.maps.GeocoderStatus.OK)
                {
                    map.setCenter(results[0].geometry.location);
                    var marker = new google.maps.Marker(
                    {
                        map: map,
                        position: results[0].geometry.location,
                        title: 'Sie suchten nach:' + ' ' + address
                    });
                }

            else if(status == google.maps.GeocoderStatus.ZERO_RESULTS){
                window.alert = function(){}
            }

            else
            {
                alert("An unknown error occured. Refresh the page or contact the IT team! Error: '" + status + "'");
            }
    });
});

我得到了这个HTML表单:

<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
    <input type="text" id="address" name="address" placeholder="Enter a zip code" style="width:250px;" onkeypress='filterTextbox(event)' />
    <input type="submit" id="submit" name="submit" value="Submit" />
</form>

如果我点击submit,它应该将我的请求发送到$_POST的服务器,然后给我一个答案。之后,我想执行JavaScript代码。所以我做到了这一点:

<?php
    if(isset($_POST['submit'])){
            echo "<script>
            $(document).ready(function(){
                var address = document.getElementById('address').value + ', CH';
                geocoder.geocode(
                {'address': address},
                function(results, status){          
                    if(status == google.maps.GeocoderStatus.OK){
                        map.setCenter(results[0].geometry.location);
                        var marker = new google.maps.Marker({
                            map: map,
                            position: results[0].geometry.location,
                            title: 'Sie suchten nach:' + ' ' + address
                        });
                    }

                    else if(status == google.maps.GeocoderStatus.ZERO_RESULTS){
                        window.alert = function(){}
                    }

                    else{
                        alert('An unknown error occured. Refresh the page or contact the IT team! Error: '' + status + ''');
                    }
                });
            });
        </script>";
        }
    }
?>

它向我发送了一个答案(由于action而页面刷新),但它没有执行JavaScript代码。 JavaScript代码用于在用户在文本框中键入的位置放置标记。如果我执行“正常”,它工作正常。

希望你知道我的意思

4 个答案:

答案 0 :(得分:1)

您有语法错误

alert('An unknown error occured. Refresh the page or contact the IT team! Error: '' + status + ''');

应该是

alert('An unknown error occured. Refresh the page or contact the IT team! Error: \'' +  status + '\'');

另一个可能的原因是,在文档准备好之前,地理编码器功能尚未初始化。

在页面的某个地方,您应该拥有与此类似的代码:

google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
  geocoder = new google.maps.Geocoder();
}

您需要在此时运行脚本。

您可以确保运行脚本的方法是:

// Where you load geocoder
var race_won = false;
var load_php_script = function() {
  race_won = true;
};
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
  geocoder = new google.maps.Geocoder();
  load_php_script();
}

// Replace document.ready with this:
var php_script = function() {
  // .. your old document ready code here ..
}
if (race_won) {
  php_script();
}
else {
  load_php_script = php_script;
}

答案 1 :(得分:0)

使用ajax请求并在此请求成功后运行您的JS代码。

您正在使用jQuery,因此您可以使用:

$('#yourform-id').on('submit', function(event) {
    $.ajax('/your/url/here', {
        type: 'post',
        data: { zipcode: $('#address').val() }
    }).done(function() {
        /* your JS code after successful request goes here */
    });

    event.stopPropagation();
}

编辑:您也可以在没有ajax请求的情况下执行此操作。但重要的是将.on('submit', function(event) { /* your geocode JS code here */ event.stopPropagation(); }事件注册到您的表单,以便不会发送表单。

event.stopPropagation()阻止您的表单重新加载页面并通过HTTP发送表单数据。在早期的jQuery版本中,您返回false但现在已弃用。

因此,请将此代码添加到表单所在的HTML文件中:

$(function() { // on ready
    $('#yourform-id').on('submit', function(event) {
        var address = document.getElementById('address').value + ', CH';
        geocoder.geocode({'address': address}, function(results, status){          
            if(status == google.maps.GeocoderStatus.OK){
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    title: 'Sie suchten nach:' + ' ' + address
                });
            } else if(status == google.maps.GeocoderStatus.ZERO_RESULTS){
                window.alert = function(){}
            } else{
                alert('An unknown error occured. Refresh the page or contact the IT team! Error: '' + status + ''');
            }
        });

        event.stopPropagation();
    });
});

答案 2 :(得分:0)

您确定在回复中包含了jquery吗?你确定元素id =“地址”存在吗?浏览器的开发者控制台是否报告了一些错误?在其中使用断点,看看发生了什么。

答案 3 :(得分:0)

我了解您在按下提交按钮时尝试更新谷歌地图。我没有看到表单的必要性,除非你想在你的数据库中保存地址,但你也应该使用ajax。 如果我是对的你应该有这个:

说明:按下提交按钮时不再刷新页面,输入字段中的地址将发送到geocode函数,该函数将进行ajax调用,并且在成功status == google.maps.GeocoderStatus.OK时将执行代码来自if。

<div>
     <input type="text" id="address" placeholder="Enter a zip code" style="width:250px;" onkeypress='filterTextbox(event)' />
      <input type="button" id="submit" value="Submit" />
</div>


 $('#submit').click(function(){
            var address = document.getElementById('address').value + ', CH';
            geocoder.geocode(
            {'address': address},
            function(results, status){          
                if(status == google.maps.GeocoderStatus.OK){
                    map.setCenter(results[0].geometry.location);
                    var marker = new google.maps.Marker({
                        map: map,
                        position: results[0].geometry.location,
                        title: 'Sie suchten nach:' + ' ' + address
                    });

                    // save the address in database

                       $.ajax ({
                           url: "saveAddress.php",
                           data: {'address': address},
                           success: function() {  //
                                 alert("Should be saved in database");
                           }
                       });


                }

                else if(status == google.maps.GeocoderStatus.ZERO_RESULTS){
                    window.alert = function(){}
                }

                else{
                    alert('An unknown error occured. ');
                }
            });
        });