$("#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 的处理程序不会返回最新的帖子。这是 View :
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 %}
请帮忙。我被困住了。
最佳答案
问题出在异步回调上。换句话说,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。这样它就变得更具可读性。
关于javascript - jquery .load() 函数不返回最新帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20137159/