简体   繁体   中英

Populate html table with javascript array

I would like to fill an HTML table with a JavaScript array . But, it doesn't work and I don't know why, my "innerHTML" is not interpreted.

My variable contains the good value, but when I do this :

document.getElementById("title").innerHTML = title;

It doesn't work.

This is my code:

var title = "";
var link = "";
var date = "";
var image = "";

function get_posts() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "my_url");
xhr.onload = function () {
    if (xhr.responseText == 0) {
        alert("Vous n'avez poster aucun post");

    } else {
        var posts_array = JSON.parse(xhr.responseText);

        for (var i = 0; i < posts_array.length; i++)
        {
            title = posts_array[i][0];
            link = posts_array[i][1];
            date = posts_array[i][2];
            image = posts_array[i][3];

        }
    document.getElementById("title").innerHTML = title;
    }
}
xhr.send();
}

This is my HTML :

<table id="posts">
                <tr>
                    <th id="test">Titre</th>
                    <th>Lien</th>
                    <th>Date</th>
                    <th>Image</th>
                </tr>
                <tr>
                    <td id="title"></td>
                    <td id="link"></td>
                    <td id="date"></td>
                    <td id="image"></td>
                </tr>
            </table>

You're assigning the value of title inside your loop and then setting the innerHTML of an individual cell to title . Assuming your responseText is formatted correctly, the posts table will only ever contain the last element in your array. It seems like you need to create a new table row for each item in posts_array and add it to the posts table to get your intended result.

eg

var t = "";
for (var i = 0; i < posts_array.length; i++){
      var tr = "<tr>";
      tr += "<td>"+posts_array[i][0]+"</td>";
      tr += "<td>"+posts_array[i][1]+"</td>";
      tr += "<td>"+posts_array[i][2]+"</td>";
      tr += "<td>"+posts_array[i][3]+"</td>";
      tr += "</tr>";
      t += tr;
}
document.getElementById("posts").innerHTML += t;

You have 3 errors in your code.

  1. You overriding title , link , date and image on each iteration.
  2. You setting only title, I think you want to set all data.
  3. (Posible error) You setting only 1 post into table, probably you want to see them all.

Easiest (and most common) way to create table from array is build HTML string (with table markup), and append it to table. Unfortunately IE do not support appending html into table , to solve this you may use jquery (it will create Elements from html and append them).

Example:

var posts_array = JSON.parse(xhr.responseText);
var columns = ['title', 'link', 'date', 'image']
var table_html = '';
for (var i = 0; i < posts_array.length; i++)
{
    //create html table row
    table_html += '<tr>';
    for( var j = 0; j < columns.length; j++ ){
        //create html table cell, add class to cells to identify columns          
        table_html += '<td class="' +columns[j]+ '" >' + posts_array[i][j] + '</td>'
    }
    table_html += '</tr>'
}
$( "#posts" ).append(  table_html );

Another way is to use table dom api, this will not require jQuery:

var posts_array = JSON.parse(xhr.responseText);
var columns = ['title', 'link', 'date', 'image']
var table = document.getElementById('posts');

for (var i = 0; i < posts_array.length; i++)
{
    var row = table.insertRow( -1 ); // -1 is insert as last
    for( var j = 0; j < columns.length; j++ ){
        var cell = row.insertCell( - 1 ); // -1 is insert as last
        cell.className = columns[j]; //
        cell.innerHTML = posts_array[i][j]
    }
}

It doesn't work for me.

I want to display wordpress posts into an HTML table.

My JS :

function get_posts() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "myUrl");
    xhr.onload = function () {
        if (xhr.responseText == 0) {
            alert("Vous n'avez poster aucun post");

        } else {
            var posts_array = JSON.parse(xhr.responseText);
            var columns = ['title', 'link', 'date', 'image']
            var table_html = '';
            for (var i = 0; i < posts_array.length; i++)
            {
                //create html table row
                table_html += '<tr>';
                for (var j = 0; j < columns.length; j++) {
                    //create html table cell, add class to cells to identify columns          
                    table_html += '<td class="' + columns[j] + '" >' + posts_array[i][j] + '</td>'
                }
                table_html += '</tr>'
            }
        }
        $("#posts").append(table_html);
    }
    xhr.send();
}

My HTML :

<table id="posts">
                    <tr>
                        <th id="test">Titre</th>
                        <th>Lien</th>
                        <th>Date</th>
                        <th>Image</th>
                    </tr>
                </table>

My Web service (i'm using wordpress) :

global $current_user;
if(is_user_logged_in){
$current_user = wp_get_current_user();
}

$array = array();
$posts_array = array('author' => $current_user->ID, "post_type" => "alertes", "orderby" => "date", "order" => "DESC", "post_status" => "publish", "posts_per_page" => "10");

$posts = new WP_Query($posts_array);

if($posts->have_posts()){
    while($posts->have_posts()){
        $posts->the_post();

        $post_array = array(get_the_title(), get_the_permalink(), get_the_date(), wp_get_attachment_url(get_post_thumbnail_id()));
        array_push($array, $post_array);

    }
        echo json_encode($array);

}

else {
    echo '0';
}

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