console.log looping json data but display not

时间:2018-04-20 21:26:59

标签: javascript php jquery json

I'm trying to display json data on the page, however when sending the output to html it only displays the last id.

When using console.log it loops through each id available but not on the page output itself

var username = $("#usernameinfo").text();

$.ajax({
    type: "GET",
    dataType: 'json',
    url: "<?= base_url()?>"+"account/listings/more_user_ads",
    data: {
        "username": username,
        "pid": "<?=$this->input->get('pid')?>"
    },
    success: function(res){
        for (var i = 0; i < res.length; i++){
            var output = "";
            var object = res[i];

            output = "<p>" + object.id + "</p>";
            $("#tg-authoradsslider").html(output);
            // outputs only the id of 3 which is the last id in the loop

            console.log(output);
            /* consoles.logs 
            <p>1</p>
            <p>2</p>
            <p>3</p>*/
        }
    }
});

4 个答案:

答案 0 :(得分:4)

.html() remove older data and paste new data. that's why you are getting the last record only

use .append()

for (var i=0;i<res.length;i++){
    var object = res[i];
    var output = "<p>"+object.id+"</p>";
    $("#tg-authoradsslider").append(output);
}

Working snippet:-

var res = [
    { id: 1 },
    { id: 2 },
    { id: 3 }
];

for (var i=0;i<res.length;i++){
  var object = res[i];
  var output = "<p>"+object.id+"</p>";
  $("#tg-authoradsslider").append(output);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tg-authoradsslider"></div>

答案 1 :(得分:3)

You have two problems.

  1. You re-initialize output in each iteration setting it back to an empty string.

  2. You replace the content in HTML on each iteration so only the final one is shown.

Make the changes below to fix these issues:

Change

for (var i=0;i<res.length;i++){
    var output ="";
    var object = res[i];
    output = "<p>"+object.id+"</p>";
    $("#tg-authoradsslider").html(output);
}

To

var output ="";
for (var i=0;i<res.length;i++){
    var object = res[i];
    output += "<p>"+object.id+"</p>";
}
$("#tg-authoradsslider").html(output);

答案 2 :(得分:1)

更改循环:

在您的代码中包含这些内容 1. Template literals 2.使用append代替html

let output ="";
for (let i=0;i<res.length;i++){
    let object = res[i];
    output += `<p>${object.id}</p>`;
}
$("#tg-authoradsslider").append(output);

答案 3 :(得分:0)

由于您已经在使用jQuery,因此只需利用其中的一些内置功能。<​​/ p>

success: function(res){
    var author = $("#tg-authoradsslider");
    res.forEach( r => author.append($("<p>").text(r.id)) );
}

以下是使用模拟环境的快速演示

var res = [
    { id: 1 },
    { id: 2 },
    { id: 3 }
];

var author = $("#tg-authoradsslider");
res.forEach( r => author.append($("<p>").text(r.id)) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tg-authoradsslider"></div>

相关问题