简体   繁体   English

有没有办法只使用 ajax 用新内容更新 div

[英]is there a way to update a div with new content only using ajax

This is the div that i am updating这是我正在更新的 div

but i want to add a active class to the (li) item every time the div refreshes the active class goes away so i don`t want to refresh all the data in the (ul) but only add (li) if there is a new data in the database, with out refreshing the previous (li) items但我想在每次 div 刷新活动 class 时将活动 class 添加到 (li) 项目中,所以我不想刷新 (ul) 中的所有数据,但如果有数据库中的新数据,不刷新之前的 (li) 项

<div id="contacts">
    <ul id="rooms" class="rooms">
        <!-- This is where the data get inserted -->

        <!-- the ajax call and this  -->

        <li class='contact' data-val='<?php echo $room['id']; ?>'>
            <div class='wrap'>
                <div class='meta'>  
                    <p class='name'><?php echo $room['sender']; ?></p>
                    <p class='preview'><?php echo $room['senderemail']; ?></p>
                </div>
            </div>
        </li>


    </ul>
</div>

this is my ajax call这是我的 ajax 电话

$(document).ready(function() {
    var interval = setInterval(function(){
        $.ajax({
            url: 'rooms.php',
            success: function(data){
                $('#rooms').html(data);
            }
        });
    }, 1000);
});

in the room php在房间里 php

    $rooms = get_rooms();
    foreach($rooms as $room){
        ?>
        <li class='contact' data-val='<?php echo $room['id']; ?>'>
            <div class='wrap'>
                <div class='meta'>  
                    <p class='name'><?php echo $room['sender']; ?></p>
                    <p class='preview'><?php echo $room['senderemail']; ?></p>
                </div>
            </div>
        </li>
        <?php
    }

the get_rooms() function get_rooms() function

function get_rooms() {
        $sql = "SELECT id, sender, senderemail FROM chatroom ";
        $result = mysqli_query($GLOBALS['dbh'], $sql);
        $rooms = array();   
        while($room = mysqli_fetch_assoc($result)){
            $rooms[] = array('id'=>$room['id'], 'sender'=>$room['sender'], 
                              'senderemail'=>$room['senderemail']);
        }
        return $rooms;
}

You need to simply update your JS code like:您需要简单地更新您的 JS 代码,例如:

$(document).ready(function() {
var active_list = '';
var interval = setInterval(function(){
    $.ajax({
        url: 'rooms.php',
        beforeSend: function(){
            active_list = $('#rooms').find('li.contact.active').attr('data-val');
        }
        success: function(data){
            $('#rooms').html(data);
            $(data).find('li[data-val="' + active_list +'"]').addClass('active');
        }
    });
}, 1000);

}); });

This should solve your problem and Let me know if you still face any issue.这应该可以解决您的问题,如果您仍然遇到任何问题,请告诉我。

If I understand you correctly, your problem is that you lose the active class (which you clicked on the li container) when there is new data.如果我对您的理解正确,您的问题是当有新数据时您丢失了活动的 class (您单击了 li 容器)。

This has to do with the fact that you exchange all of the content.这与您交换所有内容的事实有关。

There are now three options.现在有三个选项。 Either任何一个

  1. You give the rooms.php the id of the currently active li-container and this script sets the active class for the affected container.你给 rooms.php 当前活动的 li-container 的 id,这个脚本为受影响的容器设置活动的 class。

  2. You transfer all the chatrooms (ids) already shown to rooms.php and only load the new ones (this means effort later with sorting).您将所有已显示的聊天室(ID)转移到 rooms.php 并仅加载新的聊天室(这意味着稍后需要进行排序)。

  3. You save the active li class and re set it after content changed (this is the fastest)您保存活动 li class 并在内容更改后重新设置(这是最快的)

fe: in your Ajax succes functions: fe:在您的 Ajax 成功功能中:

let id=0;
let active_li = $('li.active');
if (active_li.length>0) id=active_li.data('val');
$('#rooms').html(data);
if (id!=0) $('li[data-val="'+id+'"]').addClass ('active');

A few other thoughts:其他一些想法:

Note the interval of 1000ms.注意1000ms的间隔。 Possible it makes Problems if the request lasts longer than 1000ms.如果请求持续时间超过 1000 毫秒,则可能会出现问题。 This may still work well in your tests, but maybe not anymore if there are a hundred or 1000 users in your application.这在您的测试中可能仍然有效,但如果您的应用程序中有一百或 1000 个用户,则可能不再适用。

Doesn't it make sense to tell the server when you click the active room and save it in a session so that the server knows which room is active in the client?当您单击活动房间并将其保存在 session 中以便服务器知道客户端中哪个房间处于活动状态时告诉服务器是否有意义?

You Just need to push new data to the div as below just replace your line with:您只需要将新数据推送到 div 如下所示,只需将您的行替换为:

$('#rooms').append(data);

this will add new <li> in your existing <div> after the last <li>这将在最后一个 <li> 之后的现有<div>中添加新的<li> <li>

jquery append() jquery append()

To get the id of the last <li>获取最后一个<li>的 id

var lastId = $( "#rooms li" ).last().attr('id');

Once you get the last id then pass it in your ajax call.一旦你得到最后一个 id,然后在你的 ajax 调用中传递它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM