【问题标题】:Form onsubmit with php and javascript使用 php 和 javascript 提交表单
【发布时间】:2014-03-17 17:59:40
【问题描述】:

我有一个网站,它根据表单中的用户输入加载数据。我还想根据相同的输入刷新谷歌地图。不幸的是,当我提交表单时,它通过 SQL 查询正确检索数据,但刷新页面导致谷歌地图重置为原始起点。解决此问题的最佳方法是什么?

表格代码如下:

<form id="user-location" method="post" action="#" onsubmit="return codeAddress();">
                    <input id="addressInput" name="addressInput" type="text" maxlength="5">

                   <input id="submit4" value="GO" type="submit"  >

                </div>
</form>

这是谷歌地图脚本的一部分:

function codeAddress() {
  var address = document.getElementById('addressInput').value;
  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
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

【问题讨论】:

    标签: javascript php forms google-maps


    【解决方案1】:

    如果您不想重新加载页面,请不要发送onsubmit。相反,将您的 HTML 更改为...

    <div id="user-location">
        <input id="addressInput" name="addressInput" type="text" maxlength="5"/>
        <input id="submit4" value="GO" type="submit" onclick="codeAddress();"/>
    </div> 
    

    在您运行地理编码请求后,您的 Javascript 将只更新地图而不提交表单。或者,您也可以使用 jQuery 来附加点击事件,如下所示...

    $(document).ready(function () {
        $('#submit4').click(function () {
            codeAddress();
        });
    });
    

    或者您可以在其中插入整个请求。要使该工作正常进行,您将删除 onclick 事件。但是如果你不想依赖 jQuery,就使用第一个解决方案。同样,关键是不要进行完整提交。要与您的 PHP 文件进行通信,请让您的函数通过...以 JSON 格式返回结果...

    echo json_encode($geodata);
    

    ...然后使用$.getJSON 请求它,这是一个像这样工作的jQuery 实用程序...

    $.getJSON('[php script name].php[?any args]', function(data) {
        // assign your geocodes here
    });
    

    【讨论】:

      【解决方案2】:

      您希望阻止表单的默认行为,即提交,对于跨浏览器解决方案,我建议使用 jQuery 的阻止默认功能。 Check it out here.

      【讨论】:

      • 我试过 event.preventDefault();它修复了谷歌地图问题,但阻止了通过 SQL 查询提取数据。
      • 查询在哪里?相同的文件还是单独的文件?
      • 在同一个文件中
      • 好的,我相信您实际上必须在同一页面中使用 AJAX 来与运行查询的 PHP 进行通信。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      • 2012-04-27
      • 1970-01-01
      • 2013-01-10
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      相关资源
      最近更新 更多