【问题标题】:How can I show a hidden DIV if a AJAX JSON response shows the proper data?如果 AJAX JSON 响应显示正确的数据,我如何显示隐藏的 DIV?
【发布时间】:2009-08-30 02:12:11
【问题描述】:

我正在编写 AJAX/jquery 通知脚本。
目前,它在 AJAX 响应中每 10 秒返回一个完整的 fhtml 格式页面。
它返回的页面是一个 PHP 页面,它只显示应该显示的项目 (仅显示有新内容的项目,例如新邮件或新评论等。)

我想将其更改为使用 JSON,但在我的主页(父级)上,我将为每个通知项设置 DIV,默认情况下,它们将使用 CSS 隐藏 JSON 响应会告诉我应该取消隐藏哪些项目。

这就是我的基本计划,下面是一些视觉模型代码。

JSON 响应,在 10 个可能的项目中,它只会返回标有 1 的项目(表示是显示该项目)
甚至可能不需要 1,因为我只显示已经确认使用 PHP 显示的项目?

{"mail":"1", "friend_request":"1" , "comment":"1" , "photo_comment":"1"},

在主父页面上将有带有 CSS 的 DIV,以使它们像这样隐藏。 (演示只有 4 个项目)

<style type="text/css">
#mail_notification{
    display: none;
}
#friend_request_notification{
    display: none;
}
#comment_notification{
    display: none;
}
#photo_comment_notification{
    display: none;
}
</style>

<div id="mail_notification"><a href="someurl.com/mail.php?id2424">New Mail</a></div>
<div id="friend_request_notification"><a href="someurl.com/mail.php?id2424">New Friend Request</a></div>
<div id="comment_notification"><a href="someurl.com/mail.php?id2424">New Profile COmments</a></div>
<div id="photo_comment_notification"><a href="someurl.com/mail.php?id2424">New Photo Comments</a></div>

那么有人可以告诉我该怎么做吗?


这是我用于显示 ajax 通知的 CUREENT 代码,使用 OLD 方法,它还没有使用 JSON

<!-- Auto update/look for NEW notifications -->
<script type='text/javascript'> 
$(document).ready(function(){ 
     var updatenotification = function(){ 
          $('#notificationcontainer') 
               .load('/modules/member/home/notifications.inc.php') 
               .fadeIn("slow"); 
     }; 
     var auto_refresh = setInterval(function(){updatenotification();}, 5000); 
     updatenotification(); 
}); 
</script>
<!-- ENDS HERE -->

【问题讨论】:

    标签: jquery ajax json notifications


    【解决方案1】:

    将更新通知消息更改为使用 get 而不是 load,并让回调遍历 JSON 键,显示与键对应的值为 1 的 DIV。

    var updatenotification = function() {
      $('#notificationcontainer')
        .get('/modules/member/home/notifications.inc.php', null, function(data) {
          for (key in data) {
            if (data[key]) {
              $('#' + key + '_notification').fadeIn();
            }
          }
        });
    };
    

    【讨论】:

    • 哇,这似乎太简单了!既然它还没有完全编码,我应该问,有什么我应该改变的性能吗?此脚本将反复运行多次,感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    相关资源
    最近更新 更多