代码之家  ›  专栏  ›  技术社区  ›  Dante

等待javascript异步回调@http post

  •  0
  • Dante  · 技术社区  · 16 年前

    我正在实现一个小特性,有点卡住了。

    我有一个按钮可以执行一些操作,例如

    <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中定义的,我无法避免。

    提前谢谢

    2 回复  |  直到 16 年前
        1
  •  1
  •   Mike Dinescu    16 年前

    首先,您要修改onclick处理程序代码以包含如下返回语句:

    <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中重新提交表单,如上面所示,调用 子()方法 形式元素 .

        2
  •  0
  •   Guffa    16 年前

    使用常规按钮(type=“button”)而不是提交按钮,这样表单就不会被发布。改为从回调函数发布表单。