[Answer]-Fetching json data and display using jquery in Python

1👍

First of, you should consider using the JQuery on-ready function (http://api.jquery.com/ready/) :

$(function() {
   ...
});

This way your code is executed once all the html is loaded and you dont run into problems, because you switch the order of the <script>-Tag (For example into the head-section) and your button is suddenly not found.

Second, as Catherine mentioned in the Comments, you should give your button an id or class, to identify it. It should also work without that, but i just checked and that doesnt seem to work. Then you can use the CSS-Selector for the id $("#MyButton")

<button id="MyButton">My Button</button>
<script type="text/javascript">
    $(function() {
        $("#MyButton").click(function() { 
        });
    });
</script>

Next you have the JSON-Part. $.getJSON(url, data, success). So first you will need the url to the json-file. How to get the url depends on where your file is. If it is a view, include the link to the view ({% url "project.app.views.get_json" %} for example) or the static file ({{STATIC_URL}}/js/data/file.json for example). If the file is in your fixtures-dir, than you have to create a view, that loads that file and returns the content as a Response, or copy the file to one of the static-folders, depending on what you want. Expecting Javascript (Client-Side) to find a file on your Server (Server-side) wont work, without some part on the server providing the file. (For similar purposes, i have a small decorator, which renders the return-value – python-dict, array, values – of a view as json and creates an appropriate HttpResponse-Object)

The data parameter may be skipped, so the last parameter is the success-callback:

<button id="MyButton">My Button</button>
<script type="text/javascript">
    $(function() {
        $("#MyButton").click(function() { 
            $.getJSON("your url here", function(data) {
                console.log(data); #Print the data to console
            }).fail(function() {
                console.log("Something went wrong with the request!");
            });
        });
    });
</script>

From there you should be able to access the data. For more callbacks like fail() see the API: http://api.jquery.com/jQuery.getJSON/
Note, that in your snippet for adding the data to the ul you have an error with the quotes, and you could also chain the calls to append, to avoid looking up the same tag over and over again:

$("#myList")
    .append("<li>" + value.item1 + "</li>")
    .append("<li>" + value.item2 + "</li>")
    .append("<li>" + value.item3 + "</li>");
👤Daishy

Leave a comment