简体   繁体   中英

AJAX response not appending with JQuery

I'm hoping someone here can help me. I don't use JQuery or javascript very much--I'm more of a php guy. I've got some code that seems to work except for actually appending the content to the UL with JQuery. If I watch the log in firebug, I see it bringing back the correct data, but the data is never actually put into the page. I have tried .html, .load, and .append with no luck. It will always load the initial HTML from the php script in the .load, but it's hit or miss as to whether the .append or .html works even though the data is always the same. Here's what I've got:

$(document).ready(function(){
        var page = 1;

        $('#favoritesul').load("/custom/getfavorites.php"); //initial load

        //load more on click
        $('#favoritesul').on( "click", "a.paginated", function (e) {
            e.preventDefault();
            ++page; //increment page counter
            //temporarily hide the load icon
            $('#favoritesul > a.paginated').remove();
            //send AJAX
            $.ajax({
                type: 'POST',
                dataType: 'html',
                url: '/custom/getfavorites.php',
                data: { page: page}
            })
            .done(function(data) {
                $('#favoritesul').append(data);
                $('#favoritesul').append('<a href="#" class="paginated"><i class="icon-undo"></i>LOAD MORE</a></ul>');
            })
            .fail(function(){
                alert('post failed');
            });
        });
    });

As I said, if I console.log and look at the AJAX response, I'm seeing the HTML I expect, it just will not append, or even replace, the contents of the HTML. For clarity, the contents of the HTML I'm trying to append look like this:

<li class='data-item'><div class='test'><div class='padding'><div class='image-container'><a href='pagelink.php'><img class='image' src='imagesource.jpg' /></a></div><div class='header'><h2 class='heading'><a href='pagelink.php'>Video</a></h2></div></div></div></li>

And the pertinent part of the existing page looks like this prior to the first .load event:

<div class='clear'></div><ul id='favoritesul' class='someclasses'></ul>

Thanks for all of the help in advance!

You do have invalid HTML in your done() handler. Firstly #favoritesul is an UL, you can't append an anchor to it, only a LI, and secondly, you can't append partial elements, like you're trying to do by including just the closing </ul> tag.

Try appending valid HTML

.done(function(data) {
    var li = $('<li />');

    li.append(data);
    li.append('<a href="#" class="paginated"><i class="icon-undo"></i>LOAD MORE</a>');


     $('#favoritesul').append(li);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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