Hannan
Hannan

Reputation: 55

In Django how to pass JSON data to use for Ajax / jQuery?

I'm trying to use JSON data in Django to provide user option to search and select. I can load and extend data to html but not sure how to use it in jQuery. My code works just fine if I link my jQuery to some website outside my server. I mean if I can link it like that:

$.getJSON("http://meme.computer/stack/data.json", function(data) {

My code is:

views.py:

from django.shortcuts import render
from aceform.forms import RequestForm
import json

def index(request):
    form = RequestForm()
    data = open('data.json').read()
    jsonData = json.dumps(data)
    return render(request, 'aceform/base.html', {'form': form, 'jsonData': jsonData})

base.html:

{% load staticfiles %}

<!doctype html>
<html>
    <head>
      <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
      <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
      <script>
     $(function() {
        var data = JSON.parse("{{ jsonData }}");
        console.log(data)
        autoComplete = [];
            for (var i = 0, len = data.length; i < len; i++) {
                autoComplete.push(data[i].iata + ", " + data[i].name);
            }
            console.log(data);
            $( "#id_from_airport" ).autocomplete({
                source: autoComplete,
                minLength: 3
            });
            $( "#id_to_airport" ).autocomplete({
                source: autoComplete,
                minLength: 3
            });
     });
    </script>
    </head>

    <body>
        {% block content %}

        {{ form.as_p }}

        {% endblock content %}
    </body>
</html>

Upvotes: 1

Views: 2267

Answers (3)

James R
James R

Reputation: 4656

At this point here:

data = open('data.json').read()

data is already of type string.

You don't need to "turn this into json" because it's already serialized (hopefully) as json.

You can do this to prove it to yourself (and maybe check for errors along the way):

def index(request):
    form = RequestForm()
    data = open('data.json').read()
    jsonData_loaded = json.loads(data)
    jsonData = json.dumps(jsonData_loaded)
    # I note here that you aren't closing the open file data.
    return render(request, 'aceform/base.html', {'form': form, 'jsonData': jsonData})

But that would be super silly.

It might make more sense to just do:

def index(request):
    form = RequestForm()
    with opened as open('data.json'):
        data = json.load(opened)
    jsonData = json.dumps(data)
    return render(request, 'aceform/base.html', {'form': form, 'jsonData': jsonData})

I mean, it's probably also redundent to load and dump, but a.) how do you know that json on disk is valid and b.) you might carry over new line charectors or other random crap.

(I wouldn't read from disk like that anyway for this kind of thing)

The moral of the story here is, you already have a string. You could just pass it along and hope for the best on the FE side!

Edit for FE:

Oh, and then I just looked at your template.

You don't actually need the whole $.getJSON function because you already have json.

You can just do var data = JSON.parse('{{jsonData|safe}}');

and then go to town with that!

Upvotes: 0

Gao Liang
Gao Liang

Reputation: 66

You can use a safe tag to pass json data to js/jquery,just like {{ jsonData|safe }}

I see your jsonData is already a string of the format of json.

You can try this in your template like

<script>
    $(function () {
        var data = {{ jsonData|safe }}
        console.log(data)
        autoComplete = [];
        for (var i = 0, len = data.length; i < len; i++) {
            autoComplete.push(data[i].iata + ", " + data[i].name);
        }
        console.log(data);
        $("#id_from_airport").autocomplete({
            source: autoComplete,
            minLength: 3
        });
        $("#id_to_airport").autocomplete({
            source: autoComplete,
            minLength: 3
        });
    });
</script>

Upvotes: 0

Alex
Alex

Reputation: 1522

$.getJSON("{{jsonData}}", function(data)

Doesn't make sense. You are calling getJSON on rendered JSON from your view. You already have the data in your template.

Depending on what template engine you are using, you should just be able to iterate over your {{jsonData}}.

Upvotes: 1

Related Questions