0

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

To expand, just output the json blob to a variable inside a script tag in your template.
Doesn't the template language need to be in double quotes when used in javascript? that is var json_dump="{{ json_dump }}";
Great, I deleted my answer :)
Great. Yes - I found that this is the way to do it - the problem I have now is dealing with None values, where my js wants null (but not 'null'). Where should I tackle this - in the views or the js?
3

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>

1 Comment

Without the |safe modifier, the json_dump is unusable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.