Обработка JSON ответа от Django QuerySet через AJAX

Я получаю JSON-ответ от представления Django.

def loadSelectedTemplate(request):
    # request should be ajax and method should be GET.
    if request.is_ajax and request.method == "GET":
        # get the template matching the ID
        templateID = request.GET.get("templateID", None)
        # check for the template matching ID in the database.
        template = list(operationTemplates.objects.filter(templateID = templateID))
        if operationTemplates.objects.filter(templateID = templateID).exists():
            # if template found return record
            ser_template = serializers.serialize('json', template )
            return JsonResponse({"valid": True, "template": ser_template}, status=200)
        else:
            # if nick_name not found, then user can create a new friend.
            return JsonResponse({"valid": False}, status = 200)

полученный ответ может быть занесен в консоль.

// GET AJAX request
        $.ajax({
            type: 'GET',
            url: "{% url 'loadSelectedTemplate' %}",
            data: {"templateID": templateID},
            success: function (response) {
                // if valid template, add to textarea
                if (response["valid"]){
                    var template = response["template"];
                    console.log(response);
                }

Объект Json выглядит следующим образом;

{
    "valid": true,
    "template": "[{\"model\": \"opnoteannotator.operationtemplates\", 
        \"pk\": 14, 
        \"fields\": {\"templateCategory\": \"Lower Limb\", 
                     \"templateName\": \"Femoral to below knee Bypass using autologous vein\", 
                     \"templatePreopBundle\": \"WHO check list completed.\\r\\n
                                                Antibiotic Chemoprophylaxis: Co-amoxiclav / Teicoplanin / Gentamicin\", 
                    \"templateIndication\": \"CLTI with night pain / rest pain / tissue loss / infection\", 

Я хочу добавить объекты в "полях" в текстовую область на моей веб-странице. Как я могу этого добиться?

Заранее спасибо.

Может быть, вы можете попробовать:

console.log(response['template']);

Мне пришлось преобразовать AJAX-вход из view.py в объект JSON, хотя я передавал его как JsonResponse.

Это решение, кажется, работает.

 // GET AJAX request
        $.ajax({
            type: 'GET',
            url: "{% url 'loadSelectedTemplate' %}",
            data: {"templateID": templateID},
            success: function (response) {
                // if valid template, add to textarea
                if (response["valid"]){

                    //var template = response["template"];
                    var tem = response.template;

                    //convert to JSON object
                    var res = JSON.parse(tem);

                    //Empty text area
                    document.getElementById("opnoteTextArea").value =""

                    //Display in text area
                    document.getElementById("opnoteTextArea").value += "Template Name: " + res[0].fields.templateName;
                    document.getElementById("opnoteTextArea").value += "\n\nPreopBundle:\n" + res[0].fields.templatePreopBundle;
Вернуться на верх