2014-01-08 41 views
0

這是我用來創建無限分頁的腳本。如何使用ajax調用返回的json?

var pageNum = 1; // The latest page loaded 
    var hasNextPage = true; // Indicates whether to expect another page after this one 

// loadOnScroll handler 
var loadOnScroll = function() { 
    // If the current scroll position is past out cutoff point... 
    if ($(window).scrollTop() > $(document).height() - ($(window).height()*2)) { 
     // temporarily unhook the scroll event watcher so we don't call a bunch of times in a row 
     $(window).unbind(); 
     // execute the load function below that will visit the JSON feed and stuff data into the HTML 
     loadItems(); 
    } 
}; 

var loadItems = function() { 
    // If the next page doesn't exist, just quit now 
    if (hasNextPage === false) { 
     return false 
    } 
    // Update the page number 
    pageNum = pageNum + 1; 
    // Configure the url we're about to hit 
    var url = document.getElementsByName('page-url')[0].value 
    $.ajax({ 
     url: url, 
     data: {page_number: pageNum}, 
     dataType: 'json', 
     success: function(data) { 
      // Update global next page variable 
      hasNextPage = true;//.hasNext; 
      // Loop through all items 
      for (i in data) { 
       $.each(data, function(index, element) { 
       $('.fest-content-event:last').append($('<div>', { 
        text: element.name 
       })); 
       }); 
       } 
     }, 
     error: function(data) { 
      // When I get a 400 back, fail safely 
      hasNextPage = false 
     }, 
     complete: function(data, textStatus){ 
      // Turn the scroll monitor back on 
      $(window).bind('scroll', loadOnScroll); 
     } 
    }); 
}; 
     $(window).bind('scroll', loadOnScroll); 

AJAX調用返回JSON這樣的:

"[{\"pk\": 1, \"model\": \"f.event\", \"fields\": {\"description\": \"The authority_name is specified when one declares a Content Provider in Andr and points to the Content as an email message\\nstored by the Content Provider. Thus, a URI into a Content Provide\", \"title\": \"\", \"rank\": \"0\", \"f\": 1, \"user\": 1, \"pub_date\": \"2014-01-07T05:42:28.258Z\"}}]" 

我要追加返回的JSON轉換爲HTML的div在類似如下:

 {% for event in events %} 
     <div class="f-content"> 
     <div class="f-content-event"> 
     {% if event.description %} 
      {{ event.description|linebreaksbr }} 
     {% endif %} 
    </div><!-- .f-content-event--> 
    </div><!-- .f-content ends --> 
     {% endfor %} 

我怎麼能這樣做?

回答

0

只需將此json字符串加載到dict對象並將其呈現在模板上即可。

下面是小例子..

>>> import json 
>>> s = '{"foo": 6, "bar": [1, 2, 3]}' 
>>> d = json.loads(s) 
>>> print d 
{u'foo': 6, u'bar': [1, 2, 3]} 

現在你可以在你的模板中使用此字典對象。