Jus*_*ton 4 javascript jquery google-maps
我有一个JavaScript问题,我需要一个函数在运行另一个函数之前运行并完成.
这是我需要首先运行和完成的代码.如您所见,我循环遍历表单中的所有地址输入字段,并通过Google Maps API对其进行地理编码.
$('#form input:text.address').each(function() {
var address = $(this);
var Geocoder = new google.maps.Geocoder();
Geocoder.geocode({ 'address': address.val() }, function(results, status) {
// Store the results in a hidden input field.
});
});
Run Code Online (Sandbox Code Playgroud)
完全完成后 - 也就是说,在Google Maps API的所有回复都已返回后 - 我需要提交表单.这是我使用的当前ajax提交代码:
$('#form').ajaxForm(
{
success:
function() {
...
}
}
);
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是表单是在Google Maps API响应之前提交的.该ajaxForm()方法允许beforeSubmit回调函数,但仍然不等待函数完成.我意识到这是因为JavaScript是异步的,但我不确定如何解决这个特殊问题.
任何帮助表示赞赏!谢谢!
从成功处理程序调用表单提交Geocoder.geocode.由于您有多次调用同一个函数,因此请设置一个指示符以指示上次调用的完成时间,然后提交表单.
这是一种方式......
var count = $('#form input:text.address').size();
$('#form input:text.address').each(function() {
var address = $(this);
var Geocoder = new google.maps.Geocoder();
Geocoder.geocode({ 'address': address.val() }, function(results, status) {
// Store the results in a hidden input field.
count--;
if (count === 0) {
//submit form here!
}
});
});
Run Code Online (Sandbox Code Playgroud)