jquery .load()函数不返回最新的帖子

时间:2013-11-22 04:42:57

标签: javascript jquery python html django

$("#comment-post-button").click(function(){ 
    var event_id = document.getElementById('event-id').value;
    var url= '/post-comments/'+event_id +'/';
    $.post(url , {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
      content:document.getElementsByName('comment-post-content')[0].value
    }); 
    $("#refresh-comments").load("/comments/" + event_id + '/', null); 
    $("#comment-post-content").val("");  
    return false;
  });

上面的代码工作正常。但是,'/ comments /'url的处理程序不会返回最新的帖子。以下是观点:

def comments(request, event_id):
  if request.method == 'GET':
    event = get_object_or_404(Event, id= event_id)
    variables = RequestContext(request, {
      'event' : event
    })
    return render_to_response('comments.html', variables)

我正在加载要在成功发布后显示的对象但是,它没有获得最新的添加。 这是'comments.html':

{% for comment in event.comment_set.all %}
    <a href="/{{ name }}/" class="first_name">{{ comment.author.first_name }}</a>
    {{ comment.content }}<br>
    {{ comment.pub_date }}
{% endfor %}

请帮助。我被卡住了。

1 个答案:

答案 0 :(得分:2)

问题在于异步回调。换句话说,load()不等待post()完成。因此,将对应于load的代码移动到回调中。另请注意,comment-post-content的重置也是来自load方法

的回调
var data = {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
  content:document.getElementsByName('comment-post-content')[0].value
}
$.post(url , data, function(){
    $("#refresh-comments").load("/comments/" + event_id + '/', function(){
        $("#comment-post-content").val(""); 
    });
}); 

另外,请一致地使用jQuery。它以这种方式变得可读。