我有一个收集个人地址的表格。当他们点击提交时,我想对他们的地址进行地理编码,并用它来填充经纬度字段。这是我现在正在做的,它基于此处的第二个答案 submit form does not stop in jquery ajax call
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
$(document).ready(function() {
var geocoder;
var address;
$('#theform').submit(function() {
geocoder = new google.maps.Geocoder();
address = $('#id_street').val() + " " + $('#id_street2').val() + " " + $('#id_city').val() + ", " + $('#id_state').val() + " " + $('#id_zip').val();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$('#id_lat').val(results[0].geometry.location.lat().toFixed(6));
$('#id_lng').val(results[0].geometry.location.lng().toFixed(6));
$('#theform').unbind('submit');
$('#theform').submit();
} else {
$('#theform').unbind('submit');
$('#theform').submit();
}
});
return false;
});
});
</script>
和表格
<form method="POST" id="theform" action="">
<li><label for="id_street">Street</label> <input id="id_street" type="text" name="street" value="3520 Lebon Dr." maxlength="100" /></li>
<li><label for="id_street2">Street2 (optional)</label> <input id="id_street2" type="text" name="street2" maxlength="100" /></li>
<li><label for="id_city">City</label> <input id="id_city" type="text" name="city" value="San Diego" maxlength="50" /></li>
<li><label for="id_state">State</label> <select name="state" id="id_state">
...a bunch of state options...
<li><label for="id_zip">Zip Code</label> <input id="id_zip" type="text" name="zip" value="92122" maxlength="30" /></li>
<label for="id_lat">Latitude</label><input type="text" name="lat" value="0.000000" id="id_lat" />
<label for="id_lng">Longitude</label><input type="text" name="lng" value="0.000000" id="id_lng" />
</form>
lat 和 lng 字段填写得很好,但表单实际上并没有被 $('#theform').submit() 提交。要实际提交表单,您必须再次点击提交。
关于我做错了什么的想法? 如果有人问我即使地理编码不成功也想提交表单,因为在这种情况下我将使用 geopy 对地址服务器端进行地理编码。
编辑: 好的,所以我做了一个非常简单的例子,但根本无法提交工作:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#subby').click(function() {
$('#theform').submit();
});
});
</script>
</head>
<body>
<a href="#" id="subby">Submit</a>
<form id="#theform" action="javascript:alert('success!');">
<input type="submit" />
</form>
</body>
</html>
我希望在单击“提交”链接时,您会看到一个警告框,就像您单击“提交”按钮时一样,但事实并非如此。我在提交时做错了什么?
最佳答案
我刚刚弄明白了。我不小心遗漏了我发布的表单中的提交按钮。它被命名为提交。显然,这把 jquery 搞砸了(在这里感谢:jQuery doesn't submit a form)。我发布的简单示例仍然无法正常工作,我不确定为什么,但我的实际问题已解决。
关于javascript - jquery,在谷歌地图地理编码后提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6206949/