JQuery load() and .prepend()

前端 未结 2 633
谎友^
谎友^ 2021-01-25 07:11

Okay so I have the following code:

function() { 
$(\"ul#postbit\").load(\'load.php\').fadeIn(\"slow\");
}, 3000);

What I am trying to achieve i

相关标签:
2条回答
  • 2021-01-25 07:47

    The .load() method is designed to work that way, i.e., to load the Ajax response directly into the element(s) that you call it on. Try instead using one of the other Ajax methods, e.g.:

    $.get("load.php", function(data) {
        $(data).prependTo("#postbit").fadeIn("slow");
    });
    

    This assumes your "load.php" returns html including li elements, which is what you seem to be describing when you say your current code overwrites the existing list each time. If your "load.php" returns just the contents for a new li without <li> tags then you can create the li and prepend it:

    $.get("load.php", function(data) {
        $("<li/>").html(data).prependTo("#postbit").fadeIn("slow");
    });
    

    EDIT: To have it continuously reload you could wrap the above into a function that you call with setInterval(), or do something like this:

    function getMoreData() {
        $.get("load.php", function(data) {
            $(data).prependTo("#postbit").fadeIn("slow");
        }).complete(function() {
            setTimeout(getMoreData, 3000);
        });
    }
    getMoreData();
    

    This uses setTimeout() to schedule another run of getMoreData() after 3 seconds, but it does so after the previous request completes.

    0 讨论(0)
  • 2021-01-25 07:50

    You should check out the jQuery API. Here's the API for AJAX: http://api.jquery.com/category/ajax/

    $.ajax({
        url: 'load.php',
        success: function(data) {
            $("ul#postbit").prepend('<li>'+ data +'</li>');
        }
    });
    
    0 讨论(0)
提交回复
热议问题