简体   繁体   中英

JQuery using .html to past ajax data in table

I have a problem with pasting some html into a div. I think I know what I'm doing wrong but I cannot find a solution to this. I have an empty div called "allbrands". This div is getting filled with data from an POST ajax call after a button has been clicked. I have made a loop that loops through the data, but it replaces the html constantly. So how can i paste this html table without replacing everytime the content?

My div:

<div id="allbrands">

</div>

My Ajax:

<script type="text/javascript">
    $( document ).ready(function()
    {
        $('[name="getbrands"]').click(function (e){
            e.preventDefault();
            $.ajax({
                type: "GET",
                url: '/brands/all',
                success: function (data)
                {
                       for(var i = 0; i < data.length; i++) {
                           $('#allbrands').html('<h6>' + data[i] + '</h6><hr>');
                       }
                }
            });
        });
    });
</script>

The data is filled like this:
在此处输入图片说明

Change this line:

$('#allbrands').html('<h6>' + data[i] + '</h6><hr>');

to

$('#allbrands').append('<h6>' + data[i] + '</h6><hr>');

and try again.

Explanation: html() replace the old content by adding new one, append() retain old one and append new as well.

The problem is in your loop. You are overriding the div's value on each iteration. You need to append the value rather than override it:

Try this:

for(var i = 0; i < data.length; i++) {
    $('#allbrands').append('<h6>' + data[i] + '</h6><hr>');
 }

Please follow below link for more information

http://api.jquery.com/append/

Also add the

$("#allbrands").append();

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