简体   繁体   中英

jQuery/JS – Outputting objects inside an array – best practice

Need some advice. I am using a jQuery calendar plugin (which seems to be rare!) and it is completely initialised with JS. No HTML.

To add events, you have to write each event as an object inside an array:

events: [
        {
            title: "Title of event",
            start: {
                date: YYYYMMDD or "YYYYMMDD",   // "20131230"
                time: "HH.MM"                   // "12.00"
            },
            end: {
                date: YYYYMMDD or "YYYYMMDD",   // "20131230"
                time: "HH.MM"                   // "20.00"
            }
        },
        {
            title: "Title of event",
            start: {
                date: YYYYMMDD or "YYYYMMDD",   // "20131230"
                time: "HH.MM"                   // "12.00"
            },
            end: {
                date: YYYYMMDD or "YYYYMMDD",   // "20131230"
                time: "HH.MM"                   // "20.00"
            }
        }
    ],

I am using Django, and would need to write a for loop for each event into this format. So, my question is, what's the best way to do this? JSON? Is this possible? What is best practice to output data as JS objects?

Thanks in advance,

R

As required by @rdck, below is an example how it can be achieved :

Server side (PHP example) :

<?php
$arr = array();
$arr[] = array(
    'title'=>'Title of event',
    'start' => array(
        'date'=>'YYYYMMDD',
        'time'=>'HH.MM'
        ),
    'end'   => array(
        'date'=>'YYYYMMDD',
        'time'=>'HH.MM'
        ),
);

$arr[] = array(
    'title'=>'Title of event2',
    'start' => array(
        'date'=>'YYYYMMDD',
        'time'=>'HH.MM'
        ),
    'end'   => array(
        'date'=>'YYYYMMDD',
        'time'=>'HH.MM'
        ),
);
?>

In HTML

<script type="text/javascript">
    var events = '<?php echo json_encode($arr); ?>';
</script>

events is your json object which you can pass directly into your events calendar

I think, best way to do this - is AJAX-request.

But you can add json-string to context-dict and render it in template:

<script type="text/javascript">var events = {{ json_data }};</script>

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