0

ビューから結果を表示するのに問題があります。通常の HttpResponse を実行すると機能しますが、render_to_response で機能させる方法がわかりません

どんな助けでも大歓迎です。

これが私のコードです:

JQuery/AJAX

function ajaxTest() { 
    $.ajax({
        type: 'POST',
        url: '/trivia/ajax_test/',
        data: {
              recipient: document.getElementById("id_recipient").value,
              message: document.getElementById("id_message").value
              },
        success: function(result){$("#messageTable").find("tbody").append(result);} 
    });

    return false;
}

メイン HTML

<table id="messageTable">
<thead>
 ...
</thead>
<tbody>
...
{% include "trivia/trivia_ajax_messages.html" %}
</tbody>
</table>

含める -- トリビア/トリビア_ajax_messages.html

{% for message in ajax_messages %}
...
{{ message.message }}
{% endfor %}

urls.py

(r'^trivia/ajax_test/$', 'findadownload.trivia.views.ajax_test'),

ビュー.py

@csrf_exempt
def ajax_test(request):
    if request.is_ajax():
        profile = Profile.objects.get(user=request.user)
        # data received via AJAX
        recipient = request.POST.get('recipient', False)
        message = request.POST.get('message', False)
        # create a new Message
        msg = Message(sender=profile,
                          recipient=Profile.objects.get(user__username=recipient),
                          message=message)
        msg.save()

        # get messages
        get_messages = chain(Message.objects.filter(sender=profile),
                            Message.objects.filter(recipient=profile))
        message_list =  sorted(get_messages, key=lambda instance: instance.last_modified, reverse=True)

        return render_to_response('trivia_ajax_messages.html', {'ajax_messages': message_list})

    return HttpResponse("Something went wrong")
4

1 に答える 1

1
function ajaxTest() { 
    $.ajax({
        type: 'POST',
        url: '/trivia/ajax_test/',
        data: {
              recipient: document.getElementById("id_recipient").value,
              message: document.getElementById("id_message").value
              },
        success: function(result){
            var html = $(result);
            $("#messageTable").find("tbody").clear().append('<tr><td>' + html + '</td></tr>');
        } 
    });

    return false;
}


@csrf_exempt
def ajax_test(request):
    if request.is_ajax():
        //other codes here

        return render_to_response('trivia_ajax_messages.html', {
            'ajax_messages': message_list
        }, context_instance=RequestContext(request))

    return HttpResponse("Something went wrong")
于 2013-02-28T07:08:16.750 に答える