开发者

Cross Browser - Ajax or JQuery "recurring" call to Asp.Net MVC Controller Action

开发者 https://www.devze.com 2023-01-27 12:46 出处:网络
I need to have to make a call to a ASP.Net Controller Action every XX seconds (just to tell that I\'m alive). The Act开发者_运维百科ion returns nothing.

I need to have to make a call to a ASP.Net Controller Action every XX seconds (just to tell that I'm alive). The Act开发者_运维百科ion returns nothing.

Action Code:

public ActionResult StillOnline()
{
    // bla bla bla
    return new EmptyResult();
}

I understand the best way to make a "recurring" call is to use "SetInterval(function, XXX) but it seems that my trials work with one browser and not others.

My Current JQuery call:

        <script type="text/javascript" src="<%= Url.Content("~/scripts/jquery-1.4.1.min.js") %>"></script>

        <script type="text/javascript">
            window.setInterval(
                $.get('<%: Url.Action("StillOnline", "Account") %>'), 10000);
        </script>

This, for example, works well with Chrome (executes every 5 seconds) but not with IE (it only gets called once) and never throws an error.

QUESTION:

What is the best Cross Browser way to call an Controller Action on the server that returns nothing ??


You don't need to wrap your call into the DOM ready event as you are not manipulating any DOM elements and the following should work cross browser:

<script type="text/javascript">
    window.setInterval(function() { 
        var url = '<%: Url.Action("Available", "ControllerName") %>';
        $.get(url);
    }, 10000);
</script>

Also notice the parenthesis () after the anonymous function declaration which you were missing in your initial declaration (the one passed to setInterval and not the one passed to document.ready).

Also it is a good idea to have your controller action always return something and not null (even if this something is an empty result):

public ActionResult Available()
{
    return new EmptyResult();
}


Try

return JSON(true);

in your Action. Your javascript is failing to parse JSON response it expects when you return null.


<script type="text/javascript">

function DoCallBack() {
        var url = '<%: Url.Action("Available", "ControllerName") %>';
        $.getJSON(url, null, null);
}

window.setInterval("DoCallBack()", 10000);

</script>


public ActionResult Available()
{
    return "[]";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消