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: SERVER (VIEW FUNCTION) RETURNS:
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
HTML PAGE:
...
..
datatype:'html'
}).done(function(data) {
$("#received_answer").html(data);
}); // closing ajax group
console.log(value);
}); // closing the click function
});// closing document ready
</script>
I get this: ('key1', 'value1')('key2', 'value2')
EDITED: I need to tabulate the results, so something like this
$("#respuesta").html("<h5>" data.heating "</h5>");
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.
CodePudding user response:
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
console.log(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
$("#respuesta").html("tableHTML);