【问题标题】:Wagtail asynchronous call to Page model method from JSWagtail 从 JS 异步调用 Page 模型方法
【发布时间】:2018-03-22 09:58:24
【问题描述】:

我正在尝试在 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'^$') 访问页面模型中的所有 url,但不能使其从 AJAX 方法中的 url 到达方法。

知道怎么做吗?

【问题讨论】:

  • 发出 ajax 请求时浏览器网络面板显示什么?您能看到正在发出的请求,并且 URL 看起来是否正确?如果是这样,您收到的响应的状态码是什么?
  • 这是它返回的内容:POST 127.0.0.1:8000/gallery/loadImages 404 (Not Found)
  • 我将它作为普通的 django 使用,并将 urls.py 和 views.py 添加到 wagtail 应用程序并运行。无法使其与 RoutablePageMixin 一起使用。

标签: django asynchronous mixins wagtail


【解决方案1】:

我认为这是因为您在 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/$')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    相关资源
    最近更新 更多