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

标签 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 的处理程序不会返回最新的帖子。这是 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/

相关文章:

python - 如何使用顶点和边的分类属性在图形工具中绘制颜色?

python - 使用 python 访问亚马逊 s3 存储桶子文件夹

javascript - PHP Ajax mysql 选择 onload

javascript - 在下划线模板中进行项目查找/映射

javascript - 克隆行时清除隐藏输入

jquery - Jscrollpane 移动内容

javascript - Angular2 Promise 返回未定义

javascript - 在具有 Opera Mini 的功能手机上,选择要上传的文件是否可以在没有 JavaScript 的情况下触发 UI 更改?

jquery - $.Deferred 与新的 $.Deferred

python - 尝试使用 Selenium 单击按钮时出错