Populate html table with javascript array

后端 未结 3 1433
情话喂你
情话喂你 2021-01-21 12:32

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 co

3条回答
  •  长发绾君心
    2021-01-21 13:11

    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 += '';
                    for (var j = 0; j < columns.length; j++) {
                        //create html table cell, add class to cells to identify columns          
                        table_html += '' + posts_array[i][j] + ''
                    }
                    table_html += ''
                }
            }
            $("#posts").append(table_html);
        }
        xhr.send();
    }
    

    My HTML :

    Titre Lien Date Image

    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';
    }
    

提交回复
热议问题