Django render_to_response()返回空响应

时间:2014-12-02 11:37:17

标签: jquery python html ajax django

我希望能够返回HTML响应并使用AJAX将其附加到我的DOM,但它返回一个空响应。

AJAX

$(document).on('click', '.load-more-posts', function(){
    var $this = $(this);
    var userID = $('.user_id').val();
    var request = $.ajax({
          url: "/mysite/load_more/",
          type: "POST",
          data: { user_id : userID },
          dataType: "html"
        });
        request.done(function( msg ) {          
            console.log(msg);
        });
})

urls.py

url(r'^load_more_posts/$', views.load_more, name='loadMore'),

views.py

def load_more(request):
    if request.is_ajax():

        loaded_post = request.session['loaded']
        more_posts = Posts.objects.all()[loaded_post:5]
        request.session['loaded'] += 5
        context = {'more_posts':more-posts}

        return render_to_response('mysite/loadmore.html', context)

loadmore.html

this is all I have in the html file

{% for article in more_posts %} 
    <div class='user-article'>
        <h3> {{article.header}} </h3>
        <p> {{article.content}}</p>
    </div>
{% endfor %}
  1. 为什么这会返回空响​​应?
  2. 我是否需要在html中添加<!DOCTYPE html><html lang="en"><head>
  3. 我如何{% load staticfiles %}

1 个答案:

答案 0 :(得分:1)

这一行:

more_posts = Posts.objects.all()[loaded_post:5]
如果loaded_post大于5,则

无法工作,因为切片列表[6:5]将返回[]。你可能意味着:

more_posts = Posts.objects.all()[loaded_post:loaded_post+5]