2016-04-01 28 views
0

我只想在执行“removeDocx”函数时才更新页面。 但在我的情况下,定时器的超时被认为是“等待”功能的完成。 问题在哪里,我该如何解决? 有的代码的示例:

$(function() { 
    $.when(wait()).done(function() { 
     location.href = location.href; 
    }); 
}); 
function wait() { 
    var pm = { ISN_DOC: GetrcId(document.location.href) }; 
    if (isNaN(pm.ISN_DOC)) 
     setTimeout(wait, 500); 
    else removeDocx(); 
} 
function removeDocx() { 
    var def = $.Deferred(); 
    var url = "MinPrj/Collage.asmx/clearPattern?isn_doc=" + pm.ISN_DOC; 
    $.ajax({ 
     type: 'POST', 
     url: rootpath + url, 
     contentType: 'application/json' 
    }).done(function (r) { 
     def.resolve(); 
    }).fail(def.reject()); 
    return def; 
} 
+0

您正在调用'wait()'并将其返回值传递给'$ .when'。由于“等待”不会返回任何内容,因此您如何期望它可以正常工作? –

+0

您没有'$ .ajax'的'data'参数。当你没有内容时,为什么你要设置'application/json'的内容类型? – Quentin

回答

1

首先修复你的removeDocx函数。 $.ajax已经返回延期对象:

function removeDocx() { 
    var url = "MinPrj/Collage.asmx/clearPattern?isn_doc=" + pm.ISN_DOC; 
    return $.ajax({ 
     type: 'POST', 
     url: rootpath + url, 
     contentType: 'application/json' 
    }); 
} 

现在wait函数返回一个延迟,以及(它与$.when工作)。问题在于你必须在wait之间的不同(伪递归)调用之间共享状态。像这样的东西可能会奏效:

function wait(def) { 
    if (!def) { 
     var def = $.Deferred(); 
    } 
    var pm = { ISN_DOC: GetrcId(document.location.href) }; 
    if (isNaN(pm.ISN_DOC)) { 
     setTimeout(function() { 
      wait(def); 
     }, 500); 
    } else { 
     $.when(removeDocx()).then(def.resolve); 
    } 
    return def; 
} 

代码的其余部分保持原样,即你叫wait()没有ARGS。

+0

谢谢。有用!我更清楚地使用被拒绝的对象。 –

+0

但它不完全正确。如果改为 location.href = location.href;写location.reload(); - 有一个无限循环。 我不能通过点击项目按钮来实现这个功能。 –

2

the documentation

jQuery.when(deferreds)
deferreds
类型:延迟
零个或多个延迟的对象,或纯JavaScript对象。

你传递一个正函数,而不是一个Deferred对象等等......

如果一个参数传递给jQuery.when(),它是不是一个延期或承诺,这将是视为已解决的延迟,任何已完成的附加回调将立即执行。

+0

感谢您的回答。你帮了我。 –