用PHP和JavaScript表单onsubmit [英] Form onsubmit with php and javascript

查看:83
本文介绍了用PHP和JavaScript表单onsubmit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a site that loads data based on user input in a form. I also want to refresh a google map based on that same input. Unfortunately, when I submit the form, it correctly retrieves the data through an SQL query but refreshes the page causing the google map to reset to the original starting point. What is the best way to resolve this?

这是表单代码:

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

以下是Google地图脚本的一部分:

Here is part of the script for google maps:

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

推荐答案

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

If you don't want to reload your page, don't do an onsubmit. Instead, change your HTML to...

<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附加click事件.

Your Javascript would then just update the map without submitting the form after you've ran your geocoding request. Alternatively you can also use jQuery to attach the click event like so...

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

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

Or you could insert your entire request in there. To make that work, you would remove the onclick event. But if you don't want to have a dependency on jQuery, just use the first solution. Again, the key is not to do a full submit. To communicate with your PHP file, have your function return the results as JSON via...

echo json_encode($geodata);

...,然后使用$.getJSON请求它,这是一个jQuery实用程序,其工作原理如下...

... and then request it with $.getJSON which is a jQuery utility which works like so...

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

这篇关于用PHP和JavaScript表单onsubmit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆