简体   繁体   English

我可以通过回调添加getJSON的done()函数吗?

[英]Can I add getJSON's done()-functions by callback?

On this code: 在此代码上:

 function hello(){
     alert("hello");
 }
 function hi(){
     alert("hi");
 }

 jQuery.getJSON('foo.bar',function(data){
     if (data.foobar) {
         this.done(hello);
     }
     alert('callback done');
 }).done(hi);

and assuming this returns from foo.bar 并假设这从foo.bar返回

{"foobar":true}

I like to have the alerts in this order: 我喜欢按以下顺序发送警报:

  1. callback done 回调完成
  2. hi
  3. hello 你好

But I can not add a done() -function in the success -callback. 但是我不能在success回调中添加done()函数。

Have you a hint how I add a done() -function inside of the success -callback? 您是否暗示我如何在success回调中添加done()函数?

The jqXHR object is the third argument to the callback function: jqXHR对象是回调函数的第三个参数:

jQuery.getJSON('foo.bar', function(data, textStatus, jqXHR) {
    if (data.foobar) {
        jqXHR.done(hello);
    }
    alert('calback done');
}).done(hi);

I don't think you should be trying to combine callbacks and done() handlers in the first place, let alone interweaving them like this. 我不认为您应该首先尝试将回调和done()处理程序结合起来,更不用说像这样将它们交织在一起了。 Just use one done() handler: 只需使用一个done()处理函数即可:

jQuery.getJSON('foo.bar').done(function (data) {
    hi();
    if (data.foobar) {
        hello();
    }
});

Or if you are worried about a failure in hi() preventing the rest from executing, you can pass them to done() separately: 或者,如果您担心hi()的失败会阻止其余代码执行,则可以将它们分别传递给done()

jQuery.getJSON('foo.bar').done(hi, function (data) {
    if (data.foobar) {
        hello();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM