2014-12-02 147 views
0

我希望能夠通過AJAX返回HTML響應並將其附加到我的DOM,但它返回的是空響應。Django render_to_response()返回空響應

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. 我需要把<!DOCTYPE html>,<html lang="en">,<head>在html中嗎?
  3. 我如何{% load staticfiles %}
+0

我不知道靜態文件和你的問題有什麼關係。 – 2014-12-02 11:43:48

回答

1

這行:[:5 6]將返回[]如果loaded_post大於5,由於切片列表

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

將無法​​正常工作。你大概的意思是:

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

這樣做了。如預期。 – Yax 2014-12-02 11:58:13