简体   繁体   English

jQuery使用.html粘贴表中的Ajax数据

[英]JQuery using .html to past ajax data in table

I have a problem with pasting some html into a div. 我在将一些html粘贴到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". 我有一个空的div,称为“ allbrands”。 This div is getting filled with data from an POST ajax call after a button has been clicked. 单击一个按钮后,该div充满了来自POST ajax调用的数据。 I have made a loop that loops through the data, but it replaces the html constantly. 我做了一个循环遍历数据的循环,但是它不断替换html。 So how can i paste this html table without replacing everytime the content? 那么,如何在不替换每次内容的情况下粘贴此html表?

My div: 我的div:

<div id="allbrands">

</div>

My Ajax: 我的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. 说明: html()通过添加新内容来替换旧内容, append()保留旧内容并附加新内容。

The problem is in your loop. 问题出在你的循环中。 You are overriding the div's value on each iteration. 您将在每次迭代中覆盖div的值。 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/ http://api.jquery.com/append/

Also add the 同时添加

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

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

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