Wagtail异步调用JS的Page模型方法

时间:2018-03-22 09:58:25

标签: django asynchronous mixins wagtail

我正试图在Wagtail运行网站中实现一系列懒惰的图像。

我正在尝试使用RoutablePageMixin:http://docs.wagtail.io/en/v1.13.1/reference/contrib/routablepage.html

我的页面模型:

class Gallery(RoutablePageMixin, Page):
    #I have removed all the code for readability

    @route(r'^gallery/loadImages/')
    def lazy_load_images(self, request):
        I want to hit this method with the JS call.
        pass


    class Meta:
        verbose_name = "Gallery"

我的JS代码:

(function($) {
  $('#lazyLoadLink').on('click', function() {
    var link = $(this);
    var page = link.data('page');
    $.ajax({
      type: 'post',
      url: 'gallery/loadImages/)',
      data: {
        'page': page,
        'csrfmiddlewaretoken': window.CSRF_TOKEN // from index.html
      },
      success: function(data) {
        debugger;
      },
      error: function(xhr, status, error) {
        debugger;
      }
    });
  });
}(jQuery));

如果我想,我可以使用@route(r' ^ $')访问页面模型中的所有网址,但无法通过AJAX方法中的网址访问该方法。

知道怎么做吗?

1 个答案:

答案 0 :(得分:0)

我认为这是因为你在AJAX调用网址中缺少一个前导/(以及一个额外的)字符?)。尝试将url更改为/gallery/loadImages/,如下所示:

$.ajax({
  type: 'post',
  url: '/gallery/loadImages/',
  data: {
    'page': page,
    'csrfmiddlewaretoken': window.CSRF_TOKEN // from index.html
  },
  success: function(data) {
    debugger;
  },
  error: function(xhr, status, error) {
    debugger;
  }
});

作为旁注,您需要考虑在路线末尾添加$字符,以便它只与/gallery/loadImages/ 完全匹配。否则它也会匹配/gallery/loadImages/foobar之类的路线。我将其更改为:@route(r'^gallery/loadImages/$')