Ajax请求后的setInterval停止Ajax、setInterval

2023-09-10 13:24:29 作者:统领全世界

我使用Asp.net MVC,我想我的部分观点,刷新的间隔,而它,直到我做一个不相关的Ajax请求,那么它会停止。

I'm using Asp.net MVC and I want my partial view to refresh on an interval, which it does until I make an unrelated Ajax request, then it stops.

下面是一些简单的剪刀来说明这个问题。

Here are a few simplified snips to illustrate the problem.

在AjaxRefresh.js:

in AjaxRefresh.js:

function ajaxRefresh()
{
    var f = $("#AjaxForm");
    $("#AjaxLoading").show();
    $.post(f.attr("action"), f.serialize(), function (context) {
        $("#AjaxDiv").html(context);
        $("#AjaxLoading").hide();
    });
}
setInterval(ajaxRefresh, 1000);

在Index.aspx的:

in Index.aspx:

<script type="text/javascript" src="../../Scripts/AjaxRefresh.js"></script>
<div id="AjaxDiv">
    <% Html.RenderPartial("Computers", Model, ViewData); %>
</div>

和这Computers.ascx:

and this in Computers.ascx:

<% Ajax.BeginForm("Index", new { groupName = Model.Name }, new AjaxOptions() { HttpMethod = "Post", LoadingElementId = "AjaxLoading", UpdateTargetId = "AjaxDiv" }, new { id = "AjaxForm" }); Html.EndForm();%>

<%= Ajax.ActionLink("Send", "Index", new { groupName = Model.Name, data="blah" },
        new AjaxOptions() { HttpMethod="Post", LoadingElementId="AjaxLoading", UpdateTargetId="AjaxDiv" }) %> 

如果你点击发送链接,一切仍然有效,但页面会自动停止刷新。 我试着订阅的AJAX事件,但Sys.WebForms.PageRequestManager.getInstance()是不确定的。

If you click the "Send" link, everything still works, but the page stops refreshing automatically. I've tried subscribing to the ajax events, but Sys.WebForms.PageRequestManager.getInstance() is undefined.

推荐答案

我不知道为什么会发生,但我曾在过去与jQuery阿贾克斯刷新和setInterval类似的问题。最后,我切换到一个重复的setTimeout和没有任何问题:

I'm not sure why that would happen, but I have had similar issues in the past with jQuery Ajax refreshes and setInterval. In the end, I switched to a repeating setTimeout and didn't have any problems:

function onLoad() {
    setTimeout(ajaxRefresh, 1000);
} 

function ajaxRefresh()
{
    var f = $("#AjaxForm");
    $("#AjaxLoading").show();
    $.post(f.attr("action"), f.serialize(), function (context) {
        $("#AjaxDiv").html(context);
        $("#AjaxLoading").hide();
    });
    setTimeout(ajaxRefresh, 1000);
}