如何显示一个微调,同时等待在秘银JS AJAX请求?JS、AJAX

2023-09-10 16:40:47 作者:半阙相思

我用秘银JS的一个项目,我无法理解,究竟如何去挂接到Ajax生命周期。就像如果我有一个Ajax请求需要一段时间,我想表现出微调。 pretty的基本的,但我似乎无法弄清楚如何可能发生。

I'm using Mithril JS in a project and I'm having trouble understanding exactly how to go about hooking into the Ajax lifecycle. Like if I have an Ajax request takes awhile, I want to show a spinner. Pretty basic, but I can't seem to figure out how that can happen.

欲使用相同的容器离心器作为Ajax请求正在寻找的内容。

I want to use the same container for the spinner as the content that the Ajax request is looking for.

下面是我的设置:

var Thing = function (data) {
  var p = m.prop;
  this.title = p(data.title);
  this.timestamp = p(moment.unix(data.timestamp));
}

Thing.list = function(options) {
  m.request({method: "GET", url: "/things.json", type: Thing, background: true});
};

MyApp.components.thingsList = {
  controller: function ThingListController() {
    this.things = m.prop([]);
    Thing.list().then(this.things).then(m.redraw);
  },

  view: function thingListView(ctrl) {
    return m('div#thing-tab', [
      m('ul#things', [
        ctrl.things().map(thingView)
      ])
    ]);
  }
};

function thingView(thing) {
  ...some view stuff...
}

我已经得到了它的工作就是我想要的,但我只是无法弄清楚如何挂钩到了AJAX的生命周期。再次,我只是想表明一个微调当请求开始,然后替换成Ajax请求的结果。

I've got it working the way I want, but I just can't figure out how to hook into the ajax lifecycle. Again, I just wanna show a spinner when the request starts and then replace that with the result of the ajax request.

任何及所有的帮助是极大的AP preciated!

Any and all help is greatly appreciated!

谢谢

推荐答案

一种方法是将包装 m.request 在另一个函数,返回无论是完成状态(根据您通过m.request承诺链中设置的标志),和数据,然后使用背景:真正的选项,以prevent重绘的推迟,还绑定 m.redraw 应许链,才能有发生重绘请求之后。

One way is to wrap m.request in another function that returns both the completion state (based on a flag that you set via the m.request promise chain), and the data, and then use the background: true option to prevent the deferral of the redraw, and also bind m.redraw to the promise chain in order to have redrawing happen after the request.

这本来是描述如下:https://github.com/lhorie/mithril.js/issues/192

var requestWithFeedback = function(args) {
  var completed = m.prop(false)
  var complete = function(value) {
    completed(true)
    return value
  }
  args.background = true
  return {
    data: m.request(args).then(complete, complete).then(function(value) {
      m.redraw()
      return value
    }),
    ready: completed
  }
}

var MyController = function() {
  this.things = requestWithFeedback({method: "GET", url: "/things"})
}
var myView = function(ctrl) {
  return !ctrl.things.ready() ? m("img[src=loading.gif]") : m("ul", [
    ctrl.things.data().map(function(thing) {
      return m("li", thing.name)
    })
  ]) 
}

m.module(document.body, {controller: MyController, view: myView})