[英]Form onsubmit with php and javascript
我有一个网站,可以根据用户输入的表单来加载数据。 我也想根据相同的输入刷新Google地图。 不幸的是,当我提交表单时,它会通过SQL查询正确检索数据,但会刷新页面,从而导致Google地图重置为原始起点。 解决此问题的最佳方法是什么?
这是表单代码:
<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地图脚本的一部分:
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更改为...
<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事件。
$(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
});
您正在寻求防止表单的默认行为(即提交),对于跨浏览器的解决方案,我建议使用jQuery的prevent default函数。 在这里查看。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.