Django div 重新加载 - POST 后的 ajax GET 未获取最新的数据库模型实例

在类似聊天的应用程序中,我使用 ajax 调用来发布新消息并更新页面上显示的消息,而无需重新加载整个页面。我的 ajax 发布工作调用 - 在数据库中创建了一个新的消息实例。但是,之后当我进行 ajax 调用以获取所有消息时,结果查询集中缺少新消息。如果我完全刷新页面,我可以看到所有消息,但这不是我想要的。


HTML 消息模板:


    {% for message in messages %}

    <p>

        {{ message.content }}

    </p>

    {% endfor %}

HTML 聊天模板:


<div id="chat">

    {% include "messages.html" %}

</div>


<form id="post-message-form", method="post" enctype="multipart/form-data">

    [my form goes here]

</form>

JavaScript:


$('#post-message-form').on('submit', function(event){

    event.preventDefault();

    $form = $(this);

    var data = new FormData($form.get(0));


    $.ajax({

        url: '/post/a/new/message/',

        type: 'POST',

        data: data,

        success: refresh_chat,

        cache: false,

        contentType: false,

        processData: false

    })


    return false;

}


function refresh_chat(){

    $.ajax({

        url: '/get/all/messages/,

        type: 'GET',

        success: function(json) {

            $('#chat').html(json['data']);

        }

    })

    return false;

}

意见:


import json

from django.template import loader

from .forms import MessageForm


# /post/a/new/message/

def post_message(request):

    if request.method == 'POST':

        form = MessageForm(request.POST)

        if form.is_valid():

            message = form.save()

            return HttpResponse(

                json.dumps({'status': 1,

                            'message': 'Message posted!'}),

                content_type='application/json'

            )


# /get/all/messages/

def get_messages(request):

    if request.method == 'GET':

        messages = loader.render_to_string('messages.html', context={'messages': Message.objects.all(), 'form': MessageForm()})

        return HttpResponse(

            json.dumps({'data': messages}),

            content_type='application/json'

        )

有什么想法为什么我在 POST 后调用 ajax GET 时没有获得最新的数据库数据?谢谢!


暮色呼如
浏览 239回答 1
1回答

子衿沉夜

事实证明,如果我在 ajax“完成”调用而不是“成功”上进行聊天刷新,它会起作用:$('#post-message-form').on('submit', function(event){&nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; $form = $(this);&nbsp; &nbsp; var data = new FormData($form.get(0));&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; url: '/post/a/new/message/',&nbsp; &nbsp; &nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; data: data,&nbsp; &nbsp; &nbsp; &nbsp; cache: false,&nbsp; &nbsp; &nbsp; &nbsp; contentType: false,&nbsp; &nbsp; &nbsp; &nbsp; processData: false&nbsp; &nbsp; }).done(function() {&nbsp; &nbsp; &nbsp; &nbsp; refresh_chat();&nbsp; &nbsp; });&nbsp; &nbsp; return false;}感谢您的评论!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python