S.P
S.P

Reputation: 79

Django templates using JSON

Now, I'm using Django to create a website. In order to use JSON in HTML, I made it to response JSON to template. But when I use JSON data in HTML, The data hasn't appear.

Here is my code:

views.py

def json_data(request):
    data = words.objects.all()
    return JsonResponse(list(data), safe=False)

models.py

class words(models.Model):
   word = models.CharField(max_length=20)
   value = models.FloatField(default=0)
   def __str__(self):
       return self.word

url.py

url(r'^api/json_data', views.json_data, name='json_data') 

template/result.html

<script>
     var J = {% url 'json_data' %};
     var JP = JSON.parse(J);
     document.write("JSON TEST");
     for(var obj in JP){
         document.write(obj, " : ", JP[obj], "<br>");
     }
</script>

The result isn't show anything, even "JSON TEST". I can't understand why this happens. Which part did I make wrong?

Upvotes: 1

Views: 76

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599956

You haven't actually fetched the data from Django; all you've done is create a string containing a URL, and attempted to parse that as JSON.

Instead you'll need to use Ajax to request the data from that URL, and parse the response.

Upvotes: 3

Related Questions