运行 POST 完成且页面已加载到 jQuery 时的代码?
Run code when POST has completed, and page has loaded in jQuery?
我有这个代码:
$.when($.post(...)).then(function () {
...
});
我想与 $(document).ready(...);
结合使用,以便在页面初始化时请求开始,并且 .then
函数内的所有内容在页面和 POST 请求都具有时运行加载完成。
我该怎么做?
您可以设置某个时间间隔,例如
setTimeout(function(){ //do something here }, 3000);
inside .then
或检查页面中是否存在某些 div 页面,例如
$('#someDiv') !== null
我刚刚弄明白了。
显然 $(document).ready(function () { })
不仅设置事件处理程序,而且如果页面已经加载,还会 运行 立即设置代码。所以现在我只用这个:
$.post(...).then(function () {
$(document).ready(function () {
...
});
});
仅当 POST 请求已完成且页面已完成加载时,才允许代码 运行。
jQuery 将在加载 DOM 时产生承诺。因此,您可以使用 $.when()
来等待这两个承诺。因此,您可以这样做:
$.when($.post(...), jQuery.ready.promise()).then(function(result) {
// code here
// result[0] is ajax result
});
这将使您可以立即启动 ajax 调用,但仅在页面准备就绪时才处理其结果。
我有这个代码:
$.when($.post(...)).then(function () {
...
});
我想与 $(document).ready(...);
结合使用,以便在页面初始化时请求开始,并且 .then
函数内的所有内容在页面和 POST 请求都具有时运行加载完成。
我该怎么做?
您可以设置某个时间间隔,例如
setTimeout(function(){ //do something here }, 3000);
inside .then
或检查页面中是否存在某些 div 页面,例如
$('#someDiv') !== null
我刚刚弄明白了。
显然 $(document).ready(function () { })
不仅设置事件处理程序,而且如果页面已经加载,还会 运行 立即设置代码。所以现在我只用这个:
$.post(...).then(function () {
$(document).ready(function () {
...
});
});
仅当 POST 请求已完成且页面已完成加载时,才允许代码 运行。
jQuery 将在加载 DOM 时产生承诺。因此,您可以使用 $.when()
来等待这两个承诺。因此,您可以这样做:
$.when($.post(...), jQuery.ready.promise()).then(function(result) {
// code here
// result[0] is ajax result
});
这将使您可以立即启动 ajax 调用,但仅在页面准备就绪时才处理其结果。