开发者

Creating an AJAX alert for a user when there's a server-side change

I have a site where employees can login and manage things.

Each employee has a list of To-Do Items. Items can be added to an employee's list for several different things, like a new customer signin开发者_如何转开发g up. When an item is added to an employee's list, I'd like for an ajax dialog to show on the logged-in employee screen, which they can then simply dismiss.

What's the best way of doing this? I'm using C#, MVC 3 and Razor


You could poll the server for updates using the setInterval javascript method. This will allow you to send AJAX requests to the server at regular intervals to check for updates and if some condition is met alert the user.

For example you could have a controller action like this:

[Authorize]
public ActionResult Poll()
{
    bool isUpdated = CheckForUpdates(User.Identity.Name);
    return Json(isUpdated, JsonRequestBehavior.AllowGet);
}

and in the view:

var intervalId = window.setInterval(function() {
    // send AJAX requests every 4 seconds to check for updates
    $.getJSON('@Url.Action("poll")', function(isUpdated) {
        if (isUpdated) {
            // TODO: use some fancy popup instead of an alert :-)
            alert('There are updates');
            window.clearInterval(intervalId);
        }
    });
}, 4000);

Another technique that you could use is the server pushing notifications to the client if there are updates. HTML5 WebSockets allow you to do this. The advantages is that it is far more optimized as it avoids the continuous polling and numerous AJAX requests, the drawbacks is that it is not yet widely supported by browsers. Modern browsers support it, but as it is still a draft it is subject to change, so it is not very popular over public internet. On the other hand if you have control over your users browsers it could be a very nice solution.

You might checkout the blog of this guy if you decide to go that route.


Don't use setinterval because it will fire regardless of your calling function is finished. Use settimeout instead. And call it again last inside your function.


You can use the jquery UI dialog:

http://jqueryui.com/demos/dialog/

It suits very well for your case.

Hope this helps


Use Jquery's ajax functions on the client side to poll the server for updates. For example:

$.get("/service/getNewItems/", function (data) {
        if (data != null) {
            // display new items in a div
        }
        else {
            //alert('null');
        }
    });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜