2014-01-08 5 views
0

Это сценарий, который я использую для создания бесконечной разбивки на страницы.Как использовать json, возвращаемый вызовом ajax?

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 дивы в нечто подобное, как показано ниже:

 {% 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]} 

Теперь вы можете использовать этот объект Dict в шаблоне.

Смежные вопросы