简体   繁体   English

调用await jquery.ajax时如何获取data、textStatus和jqXHR?

[英]How to get data, textStatus and jqXHR when calling await jquery.ajax?

I am using JQuery AJAX, using await.我正在使用 JQuery AJAX,使用等待。 I do not want to use the success and error callbacks and I do not want to use the .then syntax.我不想使用成功和错误回调,也不想使用.then语法。

When calling jquery ajax like so像这样拨打 jquery ajax 时

const { data, textStatus, jqXHR } = await $.ajax(url, {...});

then the variables on the left are not populated.那么左边的变量就不会被填充。

How to call jquery ajax using await and still get data , textStatus and jqXHR (similar to the success callback)?如何使用 await 调用 jquery ajax 并仍然获取datatextStatusjqXHR (类似于成功回调)?

(Simply calling const data = await $.ajax(url, {...}); works but I need access to textStatus and jqXHR .) (只需调用const data = await $.ajax(url, {...});即可,但我需要访问textStatusjqXHR 。)

you can get the 3 parameters you specified in the success option for the ajax function and do the destructuring on that anonymous function您可以获得在ajax function 的success选项中指定的 3 个参数,并对匿名 function 进行解构

    let data, textStatus, jqXHR;
    await $.ajax(url, {success: (dt, txt, jqx) => {
      data = dt;
      textStatus = txt;
      jqXHR = jqx;
    }});

or extract the function and do it like this或者提取 function 并像这样

...
const success = (dt, txt, jqx) => {
  data = dt;
  textStatus = txt;
  jqXHR = jqx;
}
...
await $.ajax(url, {success});
...

Based of the jQuery documentation (as i haven't used jQuery in many years), it seems that $.ajax returns jqXHR so one approach could be not to use await on the jqXHR object when you call await $.ajax(...) you could do something like the following instead基于 jQuery 文档(因为我已经很多年没有使用 jQuery 了),似乎$.ajax返回jqXHR所以一种方法可能是当你调用await $.ajax(...)你可以做类似下面的事情

  const jqXHR = $.ajax("https://jsonplaceholder.typicode.com/todos/1");
  const data = await jqXHR;
  const statusText = jqXHR.statusText;

  console.log({ data, statusText, jqXHR });

or if you like it as a in your example you could write a small wrapper function, or maybe it is possible to achieve with the $.ajaxSetup as well或者如果您喜欢它作为示例中的一个,您可以编写一个小包装器 function,或者也可以使用$.ajaxSetup来实现

an example of a wrapper function could be something like包装器 function 的示例可能类似于

async function ajax() { 
   return new Promise((resolve, reject) => {
     $.ajax(...arguments)
      .then((data, statusText, jqXHR) => resolve({ data, statusText, jqXHR }))
 })
}

and you can then use ajax instead of $.ajax like然后你可以使用ajax而不是$.ajax类的

const { data, statusText, jqXHR } = await ajax("https://jsonplaceholder.typicode.com/todos/1");

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

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