我正在调用一个函数来使用jQuery.post刷新当前页面的一部分,然后在该函数完成之后,我需要执行另一个函数来更新该页面上的Google Map,使用从$.post写出的更新后的HTML
我不能嵌套函数,因为DoGoogleMap()不能在RefreshSubdivisionList()函数的作用域内工作。
如何让它在调用DoGoogleMap()函数之前等待$.post完成将更新后的超文本标记语言写入页面?
function RefreshSubdivisionList() {
    var formActionScript = jQuery("#RefreshSubdivisionForm").attr('action');
    jQuery.post(formActionScript, jQuery("#RefreshSubdivisionForm").serialize()).done(function(data) {
        jQuery(".subdivision-list").html(data).show();
    }, 'text');
    return true;
}
jQuery("#RefreshSubdivisionForm").submit(function(event) {
    event.preventDefault();
    jQuery.when( RefreshSubdivisionList() ).done(function(){
        jQuery('#map_canvas').gmap('destroy');
        DoGoogleMap();
    });
    return false;
});发布于 2015-06-19 02:32:24
提供了一些机制来处理同步多个异步调用的情况。看一看:
function ajax1 {
    return $.ajax("/page1/action", {});
}
function ajax2 {
    return $.ajax("/page2/action", {});
}
var promise = $.when(ajax1, ajax2);
promise.done(function (resp1, resp2) {
  // The parameters resp1 and resp2 are the responses 
  // of their respective ajax1 and ajax2 calls.
  // Each parameter is an array that contains the ajax response
  // with the following signature:
  // [data, statusText, jqXHR]
  // See: http://api.jquery.com/jquery.ajax/#jqXHR
  // suppose the data response for ajax1 is: "Hello"
  // suppose the data response for ajax2 is: "world"
  var data = resp1[0] + " " + resp2[0];
  if ((/hello\sworld/i).test(data)) {
    console.info("Promises rules!");
  }
});在前面的示例中,我们处理success响应,但也可以以同样的方式处理failure响应。
jQuery.ajax()返回的jqXHR对象实现了Promise接口,为它们提供了的所有属性、方法和行为(有关更多信息,请参阅Deferred object )
另一种方法是创建deferred对象,并用预期结果解析每个延迟对象,最后,统一解析的响应:
var d1 = $.Deferred();
var d2 = $.Deferred();
$.when(d1, d2).done(function (resp1, resp2) {
    console.log(resp1); // "Fish"
    console.log(resp2); // "Pizza"
});
d1.resolve("Fish");
d2.resolve("Pizza");发布于 2015-06-19 02:18:40
您可以将DoGoogleMap();直接放在post的done回调中,不是吗?
然后它会在帖子完成后加载你的地图。
发布于 2015-06-19 02:43:57
要做到这一点,您需要做的就是从RefreshSubdivisionList方法返回jqXHR对象。
jQuery为像post这样的XHR请求提供deffered接口,when方法使用该接口来确定请求的状态。如果它完成了或失败了,等等。
function RefreshSubdivisionList() {
    var formActionScript = jQuery("#RefreshSubdivisionForm").attr('action');
    var postObj = jQuery.post(formActionScript, jQuery("#RefreshSubdivisionForm").serialize());
    postObj.done(function(data) {
        jQuery(".subdivision-list").html(data).show();
    }, 'text');
    return postObj;
}
jQuery("#RefreshSubdivisionForm").submit(function(event) {
    event.preventDefault();
    jQuery.when( RefreshSubdivisionList() ).done(function(){
        jQuery('#map_canvas').gmap('destroy');
        DoGoogleMap();
    });
    return false;
});https://stackoverflow.com/questions/30922803
复制相似问题