【问题标题】:Waiting for javascript async callback @ http post等待javascript异步回调@http post
【发布时间】:2009-08-04 15:11:27
【问题描述】:

我正在实现一个小功能,但有点卡住了。

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

<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;
            }
          });
}

在函数内部定义了一个回调函数,该函数执行异步操作,将城市名称写入表单字段。问题是异步回调将在页面发布后尝试写入字段。有什么可以让后期处理等待回调结果的吗?回调是在 Google Maps API 中定义的,我无法避免。

提前致谢

【问题讨论】:

    标签: javascript asynchronous callback http-post


    【解决方案1】:

    首先,您要修改 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 重新提交表单,就像我上面演示的那样,在 form 上调用 submit() 方法元素

    【讨论】:

    • 只是一个小提示:我将类型更改为按钮并且不从函数返回。这是两个答案的融合。
    • 嗯,给猫剥皮的方法还有很多……:) 但我很高兴我能帮上忙!
    【解决方案2】:

    使用常规按钮 (type="button") 而不是提交按钮,以便不发布表单。而是从回调函数发布表单。

    【讨论】:

      猜你喜欢
      • 2021-06-30
      • 2012-05-04
      • 2018-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 2018-09-22
      • 2017-06-29
      相关资源
      最近更新 更多