从Django视图将数据加载到Javascript中?

时间:2013-07-18 16:24:48

标签: javascript html django yui

我有一个看起来像这样的view.py:编辑:现在看起来像这样

def sessionscheduler(request):
    c = connection.cursor()            
    c.execute("SELECT * FROM meter_schedule WHERE id = 1")
    scheduleArray = []
    for row in c.fetchall():
        data = dict([('lastUpdate',row[1]), ('weekdaysOn',row[2]), ('weekdayChargeRateOffPeriodKwh',row[3]), ('weekdayEveningChargeOn',row[4]), ('weekdayEveningStart',row[5]),
                     ('weekdayEveningDuration',row[6]), ('weekdayDayChargeOn',row[7]), ('weekdayDayStart',row[8]), ('weekdayDayDuration',row[9]), ('weekendsOn',row[10]), 
                     ('weekendChargeRateOffPeriodKWh',row[11]), ('weekendEveningChargeOn',row[12]), ('weekendEveningStart',row[13]), ('weekendEveningDuration',row[14]), 
                     ('weekendDayChargeOn',row[15]), ('weekendDayStart',row[16]), ('weekendDayDuration',row[17])])
        scheduleArray.append((data))
    jscheduleArray = json.dumps(scheduleArray)    
    return render(request, 'sessionscheduler.html', jscheduleArray)

使用调试器我可以看到变量scheduleArray包含我想要加载到其中的所有数据。

如何在我的.js文件中加载jscheduleArray?

2 个答案:

答案 0 :(得分:2)

您生成的JavaScript可能无效。将数据从Python导出到JS的最简单方法是通过JSON。

import json
def sessionscheduler(request):
    latest_schedule_update = schedule.objects.all()
    context = {'latest_schedule_update': json.dumps(latest_schedule_update)}
    return render(request, 'sessionscheduler.html', context)

你的django-template js

<script>
    var latest_schedule_update = {{ latest_schedule_update }};
</script>

答案 1 :(得分:0)

如果您正在模仿javascript文件,请不要混用pythonjavascript,请确保将来自服务器端/ django应用程序的值放在引号中。