我正在调用一个函数来用 jQuery.post 刷新当前页面的一部分 - 然后在该函数完成后,我需要执行另一个函数来更新该页面上的 Google 地图,使用从 $.post 写出的更新的 HTML
我无法嵌套这些函数,因为 DoGoogleMap() 无法在 RefreshSubdivisionList() 函数的范围内工作。
如何让它等待 $.post 完成将更新的 HTML 写入页面,然后再调用 DoGoogleMap() 函数?
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;
});
jQuery.when() 提供了处理同步多个异步调用情况的机制。看一看:
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 ((/hellosworld/i).test(data)) {
console.info("Promises rules!");
}
});
在前面的示例中,我们处理成功响应,但处理失败响应的方式相同。
jQuery.ajax() 返回的 jqXHR 对象实现了 Promise 接口,为它们提供了 Promise 的所有属性、方法和行为(有关更多信息,请参阅延迟对象)
另一种方法是创建延迟对象,并使用预期结果解析每个延迟对象,最后统一已解决的响应:
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");
把DoGoogleMap();
直接放在post
的回调done
,不是吗?
然后它将在帖子完成后加载您的地图。
要完成这项工作,看起来您需要做的就是从 RefreshSubdivisionList
方法返回 jqXHR 对象。
jQuery post
deffered
接口提供XHR请求,这是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;
});