简体   繁体   English

jQuery / JS –在数组内输出对象–最佳实践

[英]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. 我正在使用jQuery日历插件(这似乎很少见!),并且已完全用JS初始化。 No HTML. 没有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. 我正在使用Django,并且需要将每个事件的for循环编写为这种格式。 So, my question is, what's the best way to do this? 所以,我的问题是,执行此操作的最佳方法是什么? JSON? JSON? Is this possible? 这可能吗? What is best practice to output data as JS objects? 将数据输出为JS对象的最佳实践是什么?

Thanks in advance, 提前致谢,

R [R

As required by @rdck, below is an example how it can be achieved : 按照@rdck的要求,以下是如何实现的示例:

Server side (PHP example) : 服务器端(PHP示例):

<?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 在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 events是您的json对象,您可以将其直接传递到事件日历中

I think, best way to do this - is AJAX-request. 我认为,执行此操作的最佳方法-是AJAX请求。

But you can add json-string to context-dict and render it in template: 但是您可以将json-string添加到context-dict并将其呈现在模板中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM