【问题标题】:Execute JavaScript code after $_POST request in php在 php 中的 $_POST 请求后执行 JavaScript 代码
【发布时间】:2013-12-04 07:47:45
【问题描述】:

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

$(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 代码用于在用户在文本框中键入的内容处放置一个标记。如果我“正常”执行它,它工作正常。

希望你明白我的意思

【问题讨论】:

    标签: javascript php jquery geocoding


    【解决方案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;
    }
    

    【讨论】:

    • 哦,没注意到,谢谢提示。这不是错误,您可能知道错误?
    • 也许地理编码器尚未加载?在您的第一个脚本中,您在单击事件上调用地理编码器,但在由 php 加载的脚本中,您在 document.ready 中调用它。
    【解决方案2】:

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

    【讨论】:

    • 当页面加载时,控制台没有错误,但是如果我点击按钮就会出现错误:“Uncaught TypeError: Cannot call method 'geocode' of undefined”
    • 这可能意味着地理编码器对象尚未初始化。确保在绑定提交处理程序之前加载它。
    【解决方案3】:

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

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

    <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. ');
                    }
                });
            });
    

    【讨论】:

    • 不好意思忘了说:表单是需要的,因为后面我要获取文本框的值
    • 所以当你用同样的方法更新地图时,你会保存地址或用它做其他事情
    • 是的,我从文本框中获取邮政编码,然后将其用于其他内容
    【解决方案4】:

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

    【讨论】:

    • 我以前从未使用过ajax。 “/your/url/here”是指我的 .php 文件还是只是执行 .php 文件的 url? zipcode 是 ajax 函数吗?
    • data 参数持有一个 JS 对象。并且会自动转换为zipcode=value&amp;otherparam=value2&amp;.../your/url/here 应替换为您的 PHP 脚本的 URL,该脚本提供坐标或任何您的请求。
    • 是的,我看过你的编辑。它不放置标记。就像从前一样。它刷新了页面(所以我得到了答案),但是 JavaScript 代码没有执行
    • 那么你给你的表单一个id并注册了这个事件吗?因此,要使我的示例正常工作,您必须将表单标签更改为 &lt;form id="yourform-id"&gt; 才能工作。
    • 是的,我已经完成了,但它没有帮助:/ 我现在将我的代码复制到一个新文件中并创建一个全新的结构,也许我会看到错误。
    猜你喜欢
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 2021-08-02
    • 2014-10-20
    相关资源
    最近更新 更多