取消一个jQuery AJAX调用返回前? [英] Cancel a jQuery AJAX call before it returns?

查看:92
本文介绍了取消一个jQuery AJAX调用返回前?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有打开,然后一个AJAX调用是一个jQuery的对话框。我想使它这样,如果对话框关闭或取消按钮是pressed AJAX调用被取消,其回调函数没有被调用。我能想到的一些方法来与像这样的变量做到这一点:

I have a jQuery dialog box that opens and then an AJAX call is made. I would like to make it so that if the dialog box is closed or the cancel button is pressed the AJAX call is canceled and its callback function is not called. I can think of some ways to do it with a variable like so:

  function doStuff(){
    var doCallback = true;
    $('#dialog').dialog({
      title: 'Dialog Title',
      modal: true,
      buttons: {
        Cancel: function() {
          doCallback = false;
          doSomethingElse();
        }
      }
    });
    $.get('url/url/url', function(data){
      if(doCallback){
        doTheSuccessThing(data);
      }
    });
  }

不过,不知怎的,感觉很脏,我和它没有真正的完成停止AJAX调用。是否有一个内置的方式来取消正在进行的AJAX调用?

But, somehow that feels dirty to me and it doesn't actually stop the AJAX call from completing. Is there a built-in way to cancel an AJAX call in progress?

推荐答案

好了,根据关使用的$不用彷徨函数返回的XmlHtt prequest对象的建议我想出了这一点:

Ok, so based off of the suggestion to use the XmlHttpRequest object returned by the $.get function I came up with this:

function doStuff(){
    var ajaxRequest = $.ajax({
                        url : 'url/url/url',
                        type : "GET",
                        success : function(data){
                          ajaxRequest = null;
                          doSuccessStuff(data);
                        }
                      });

    $('#dialog').dialog({
      title: 'Stuff Dialog',
      bgiframe: true,
      modal: true,
      buttons: {
        Cancel: function() {
          if (ajaxRequest)
            ajaxRequest.abort();
          doCancelStuff();
        }
      }
    });
  }

看来工作和清洁的感觉给我。

It seems to work and feels cleaner to me.

这篇关于取消一个jQuery AJAX调用返回前?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆