在服务器端发生更改时为用户创建AJAX警报 [英] Creating an AJAX alert for a user when there's a server-side change

查看:103
本文介绍了在服务器端发生更改时为用户创建AJAX警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可供员工登录和管理事物的网站.

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

每位员工都有一个待办事项列表.可以将项目添加到员工列表中以进行多种不同的操作,例如注册新客户.将某个项目添加到员工列表中后,我希望在登录的员工屏幕上显示一个ajax对话框,然后他们可以简单地将其关闭.

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 signing 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.

做到这一点的最佳方法是什么?我正在使用C#,MVC 3和Razor

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

推荐答案

您可以使用 setInterval javascript方法.这样,您就可以定期向服务器发送AJAX请求,以检查是否有更新,如果满足某些条件,则提醒用户.

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);
}

并在视图中:

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);

您可以使用的另一种技术是服务器在有更新的情况下将通知推送到客户端. HTML5 WebSockets 允许您执行此操作.优点是,由于避免了连续轮询和大量AJAX请求,因此它的优化程度更高,缺点是浏览器尚未广泛支持它.现代浏览器支持它,但由于它仍是草案,因此可能会发生变化,因此它在公共互联网上不是很流行.另一方面,如果您可以控制用户的浏览器,那将是一个很好的解决方案.

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.

这篇关于在服务器端发生更改时为用户创建AJAX警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆