Reputation: 79
I'm using Django to create Website. In order to use json in html, I send json in views.
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
And I want to parse json and use it in this form.
result.html
items: [
{text: "Java", count: "236"},
{text: ".Net", count: "382"},
{text: "Php", count: "170"},
{text: "Ruby", count: "123"},
{text: "D", count: "12"},
{text: "Python", count: "170"},
{text: "C/C++", count: "382"},
{text: "Pascal", count: "10"},
{text: "Something", count: "170"},
],
I do not know how to code JS. Please help me.
Upvotes: 1
Views: 4567
Reputation: 1515
You need to use AJAX call in order to get the data asynchronouly like the following.
Try this
def view_name(request):
html = '<div>Hello World</div>'
return JsonResponse({"data": html, "message": "your message"})
In html
<div id="test"></div>
<script>
$(document).ready(function(){
$.ajax({
type: 'POST',
dataType: 'json',
url: '/view/',
data: data,
success: function(response) {
console.log(response.message);
$('#test').append(response.data);
}
});
});
</script>
Upvotes: 1