如何使用jQuery / AJAX结果来处理render_to_response

时间:2013-02-28 04:38:37

标签: django jquery

我无法从我的视图中显示结果。 它在我做一个常规的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>

包含 - trivia / trivia_ajax_messages.html

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

urls.py

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

views.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")

1 个答案:

答案 0 :(得分: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")