简体   繁体   中英

Passing MySQL query results to Javascript/Jquery in Django

I am trying to send mysql query results in the context of my Django template to a Javascript variable. I am using pivot.js https://github.com/nicolaskruchten/pivottable which requires jquery and the jquery UI.

In the Django view:

cursor.execute(query)
data = dictfetchall(cursor)
json_data = json.dumps(data, cls=DateTimeEncoder)
context['pivot_data'] = json_data

This works and I am able to see the data in the javascript console but for some reason it is not formatted properly.

From my Django template:

{% load staticfiles %}
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<script type='text/javascript' src="{% static "js/pivot.js" %}"></script>
<script type='text/javascript'>
    var pivotData = '{{ pivot_data }}';
    $("#output").pivotUI(
        pivotData,
        {
            rows: ["XXX"],
            cols: ["YYY"]
        }
        );
</script>

The following is going to be a string (it's a JSON object that you quoted):

var pivotData = '{{ pivot_data }}';

You can do:

var pivotData = {{ pivot_data }};

But this is bad practice, as it's akin to eval-ing the JSON data (and will fail certain on special characters, as documented here ).

A better approach would be:

var pivotData = JSON.parse('{{ pivot_data }}');

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