声明jQuery AJAX调用以供稍后执行 [英] Declare jQuery AJAX call for execution later

查看:65
本文介绍了声明jQuery AJAX调用以供稍后执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以这样声明一个jQuery AJAX调用:

I could declare a jQuery AJAX call this way:

var foo = $.ajax({ ... });

但是实际上可以正确地执行该请求,对吗?

But that would actually perform the request right then and there, correct?

如何先声明AJAX调用而不先执行它,然后再调用它?像这样:

How can I declare the AJAX call without executing it initially, then call it later? Something like:

var foo = $.ajax({ ... });
// some stuff in between
foo.execute();

谢谢.

编辑 更多信息:我真正想做的是有一个函数,该函数根据参数构造一个AJAX请求,将其返回给调用代码,并由调用代码管理其状态(即能够执行,中止它等) ).因此,我不想简单地声明AJAX调用的设置,而是希望拥有$ .ajax返回的实际XHR对象,并且仅具有执行它,中止它的能力.

EDIT Little more info: What I really want to do is have a function that constructs an AJAX request based on parameters, returns it to the calling code, and have the calling code manage its state (i.e. be able to execute it, abort it, etc.). So rather than simply declare the settings for the AJAX call, I'd like to have in-hand the actual XHR object that the $.ajax returns, only with the ability to execute it, abort it, etc.

推荐答案

$.ajax返回promise对象,因此我们可以创建函数:

$.ajax returns promise object, so we can create function:

function prepareAjax(properties) {
  var defer = $.Deferred();

  var promise = defer.promise();

  return $.extend(promise, {
    execute: function () {
      return $.ajax(properties).then(defer.resolve.bind(defer), defer.reject.bind(defer));
    }
  });
}

调用此函数,例如:

var xhr = prepareAjax({ method: 'get', url: 'https://localhost:8001' })

将结果写入控制台:

xhr.then(function (result) { console.log(result) });

并推迟执行:

xhr.execute()

这篇关于声明jQuery AJAX调用以供稍后执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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