server returns list of tuples to an ajax request but back in the html I need to work on it and html(data) doesn't give a proper structure


I manage to send the ajax request to the server, and the server replies with a list of tuples or it could be a dictionary too, but back in the html that sent the request, this list or dict gets sort of turned into a string and I can’t iterate or work on it. This is because of the html(data), but I don’t know any other variant other than text(data) but that doesn’t solve the problem.
So, once I have sent that list or dict, how can I work on it (like doing iterations) I am using DJANGO.

I simplify the code because this is what matters, suppose I already have a dictionary that I turn into a list:

dictionary = {
            "key1": "value1",
            "key2": "value2"
        lista = list(dictionary.items())
        return HttpResponse(lista)

Then back in the html code that sent the request, this results don’t keep the nature of the list, but seems like a string


                }).done(function(data) {
      });  // closing ajax group
        }); // closing the click function
    });// closing document ready

I get this: ('key1', 'value1')('key2', 'value2')

EDITED: I need to tabulate the results, so something like this


won’t help, because I can’t type every single cell and row with double quotes, I would want the Django query set I can loop through.


As you note, dictionary.items() returns tuples, so that may not be the best approach.

You can use an intermediary step like converting to JSON to pass such structures

in your view

import json

dictionary = {
            "key1": "value1",
            "key2": "value2"
        json_dict = json.dumps(dictionary)
        return HttpResponse(json_dict)

and then in your javascript, you’ll get a much more javascripty looking string, which your existing code should pick up. You can also parse the string response back into a js object and use that to loop through it.

.done(function(data) {
    ///in case we need to debug, we can have a look at what is in data
    obj = JSON.parse( data);
    tableHTML = "<table><thead><th>Header1</th><th>Header2</th></thead><tbody>"
    ///iterate through properties with string keys
    for (const property in obj) {
      tableHTML += "<tr><td>"
      tableHTML += `${property}</td></td> ${obj[property]}`
      tableHTML += "</td></tr>"
    tableHTML += "</tbody></table>"
    //place the tableHTML in the document

Answered By – SamSparx

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published