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


Execute JavaScript code after $_POST request in php

我想在带有地理编码的地图上放置一个标记。我有一个工作代码:

$(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代码用于在用户在文本框中键入内容的位置放置标记。如果我"正常"地执行它,它就可以正常工作。

希望你知道我的意思

您有语法错误

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;
}

您确定在响应中包含jquery吗?您确定元素id="address"存在吗?浏览器的开发者控制台是否报告了一些错误?在其中使用断点并查看发生了什么。

我知道当你按下提交按钮时,你会尝试更新谷歌地图。我认为表单没有必要,除非你想把地址保存在数据库中,但你也应该使用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. ');
                }
            });
        });

使用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();
}

EDIT:您也可以在没有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();
    });
});