Darwin Tech
Darwin Tech

Reputation: 18919

Django passing json objects to jquery

in my view I am generating a json dump:

def myview:
    ... 
    data = list(queryset) # a query set of values
    json_dump = simplejson.dumps(data) 
    ...
    return render_to_response(request, 'results.html', { 'json_dump' : json_dump})

my template references a javascript file:

    $(document).ready(function() {
      // some stuff involving the json_dump var
      ...
    };

My question is, seeing as I cannot pass json_dump to $(document).ready(function() directly, what is the best way to get the json_dump data into the js?

Upvotes: 0

Views: 2962

Answers (2)

damon
damon

Reputation: 15128

The above answer is right, except you'll have quotes around your JSON dump which probably isn't what you want. In order to use it, you'd have to eval(json_dump), rather than just calling it as an object... I'd probably spiff it up a little like this:

<script>
  var window.json_dump = {{ json_dump|safe }};
</script>

<script>
  // Then later in your other javscript which comes AFTER the above script tags...
  $(document).ready(function() {
    alert( window.json_dump.foo );
  });
</script>

Upvotes: 3

Malcolm Box
Malcolm Box

Reputation: 4036

If I understand what you're trying to do, you want to pass a JSON blob into your template, such that it's accessible to a JS file that's referenced from the HTML?

In which case, just set up a variable to receive the value in your template:

<script type="text/javascript">
    var json_dump = "{{ json_dump }}"
</script>

And now use json_dump wherever you like in your JS.

Upvotes: 4

Related Questions