简体   繁体   中英

ajax outputs only the last record from the loop forEach

ajax the request displays only the last record from the loop, the code below:

$.ajax({
                   method: "POST",
                   url: "{{asset('/num')}}",
                   dataType: "json",
                   success: function (data) {
                       var inf;
                       var json_x = data;
                       json_x.forEach(function(item){
                           inf = '<p>'+ item['id'] +"</p>";
                       });
                       insTabl = document.getElementById('table');
                       insTabl.innerHTML = inf;

                   }
               });

sending in div id='table'

This line

inf = '<p>'+ item['id'] +"</p>";

is overwriting the value of inf each time through the loop. As a result, when the loop is over, inf simply holds the corresponding value from the last iteration.

To fix it, initialise inf as an empty string, before the loop:

var inf = "";

and then replace the line above, inside the loop, with this one, which appends to the string:

inf += '<p>'+ item['id'] +"</p>";

That way, you make the HTML string longer each time through the loop, and end up with the series of paragraphs that I assume you want.

Your loop is overwriting the inf variable each time. Instead, try adding to your string on each pass:

var inf = '';
var json_x = data;
json_x.forEach(function(item){
  inf += '<p>'+ item['id'] +"</p>";
});

I guess your problem is this line:

inf = '<p>'+ item['id'] +"</p>";

You override the old value, instead of just adding the new value (what I guess is what you are trying). So you might try it like this:

let inf = ""; // you could/should use "let" instead of "var"

//codeline in the callback:
inf += "<p>"+ item['id'] +"</p>";

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