tags:

views:

27

answers:

2

Hi,

I have a json object that i send as a template variable to my html template. If i have an external .js file what is the best way to pass it to it?

I read on another thread to declare the var inside the <script> tag in the <header>, but that would open up security issues? What is the standard way?

Thanks, David

A: 

I think the standard way is probably making an ajax request (I recommend using jQuery for this) from the javascript to your view to retrieve the json object.

Matthew J Morrison
what if i wanted to load the json object with the webpage load and not make a separate jqueryget? is this non standard?thanks again!
David Hsu
you could also have something like <script type="text/javascript" src="/path/to/some/view/that/returns/json"></script> and have your view return a string with a javascript content-type like this: "var json = {watever:'your json is here'};"
Matthew J Morrison
A: 

I believe a JSON object can be passed to a template like any other template variable. Let us assume that you are passing a queryset as JSON:

def my_view(request, *args, **kwargs):
    queryset = MyModel.objects.filter(**conditions)
    from django.core.serializers import serialize
    json = serialize("json", queryset)
    context = dict(json = json)
    render_to_response(..., context, ...)

And inside the template:

<script>
    var data = {{ json }};
</script>
Manoj Govindan