Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

241
Visualizações
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: 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.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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);
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda