我执行的卡住一个小功能,善良的。

我有一个按钮以执行某些动作,比如

<input type="submit" value="My Button" onclick="javascript:DoSomething();" />

当用户点击该按钮的功能的DoSomething被调用。

    function DoSomething()
    {
        var geocoder = new GClientGeocoder();
        geocoder.getLocations(map.getCenter(), function SetField(response)
          {
            if (!response || response.Status.code != 200) 
            {
               alert("Status Code:" + response.Status.code);
            } 
            else 
            {
                var place = response.Placemark[0];
                $('#someHiddenField')[0].value = place.AddressDetails.Country.CountryNameCode;
            }
          });
}

内的回调函数被定义的功能,其执行在一个形式字段中写入一个城市名称的异步操作。问题是,异步回调将尝试在网页发布后在现场写。有什么是我可以使后处理等待回调的结果?回调谷歌地图API中定义,我不能避免它。

在预先感谢

有帮助吗?

解决方案

首先,你要修改的onclick处理程序代码,包括return语句,像这样:

<input type="submit" value="My Button" onclick="javascript:return DoSomething();" />

如果它的工作在异步回调然后修改DoSomething的函数返回false,以便SUMIT将被取消。而修改异步回调后的形式完成的时候。

function DoSomething(doPost)
{
        var geocoder = new GClientGeocoder();
        geocoder.getLocations(map.getCenter(), function SetField(response)
          {
            if (!response || response.Status.code != 200) 
            {
               alert("Status Code:" + response.Status.code);
            } 
            else 
            {
                var place = response.Placemark[0];
                $('#someHiddenField')[0].value = place.AddressDetails.Country.CountryNameCode;

                // resubmit the form here 
                $('#yourFormID').submit();
            }
          });

         return false; // cancel the submitting of the form
}

另一种方法是将包括 onsubmit处理您的表格上,并使用一个全局标志来确定形式提交允许(即如果有没有异步回调仍然在飞行中)。当异步回调返回你清除该标志和从JavaScript重新提交表单等我以上证实的,呼叫的 提交()方法 形式元件

其他提示

使用的,而不是一个提交按钮以便在窗体不贴常规按钮(类型=“按钮”)。后从回调函数,而不是形式。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top