Output php data into jquery array?

前端 未结 2 1042
礼貌的吻别
礼貌的吻别 2021-01-28 19:22

I\'m creating a timeline using timesheet.js. The data will be input via custom fields in Wordpress. I want to be able to output that php data into the jquery array. Is that poss

相关标签:
2条回答
  • 2021-01-28 19:30

    Yes, you need to echo <script> tags and you can generate any Javascript you want:

    <?php
    echo '<script>';
    if( have_rows('timeline') ):
        echo 'var foo = ['
        while ( have_rows('timeline') ) : the_row();
            echo '"'.the_sub_field('start_date').'",';
            echo '"'.the_sub_field('end_date').'",';
            echo '"'.the_sub_field('description').'",';
            echo '"'.the_sub_field('name').'"';
        endwhile;
        echo '];';
    endif;
    echo '</script>';
    ?>
    
    0 讨论(0)
  • 2021-01-28 19:35

    It's quite simple to do this, really: just construct the array in php, and echo its json_encoded value:

    <?php
    $array = array();
    if( have_rows('timeline') ) {
        while ( have_rows('timeline') ) : the_row();
            $array[] = array(
                the_sub_field('start_date'),
                the_sub_field('end_date'),
                the_sub_field('description'),
                the_sub_field('name')
            );
        endwhile;
        echo '<script> var theArray = '.json_encode($array).';</script>';
    } ?>
    

    Job done, you now have a JS variable called theArray, and its value will be an array of arrays, containing all of the data you need to create new Timesheet('timesheet', 2002, 2013, theArray);

    0 讨论(0)
提交回复
热议问题