【问题标题】:ajax function not working after adding async and await keywords添加 async 和 await 关键字后,ajax 函数不起作用
【发布时间】:2020-07-12 01:58:08
【问题描述】:

下面提到的代码工作正常。

$.ajax({
   url: '?module=abc&action=xyz',
   //Ajax events
   beforeSend: function (e) {
     //
   },
   success: function (e) {
       const URL1 = '?module=mno&action=pqr';
        fetch(URL1);
   },
   error: function (e) {
     alert('error ' + e.message);
   },
   // Form data
   data: formData,
   type: 'POST',
   //Options to tell jQuery not to process data or worry about content-type.
   cache: false,
   contentType: false,
   processData: false
});

但是,如果我添加 asyncawait 它将不起作用,也不会在控制台中给出任何错误。如下代码:

$.ajax({
   url: '?module=abc&action=xyz',
   //Ajax events
   beforeSend: function (e) {
     //
   },
   success: async function (e) {
       const URL1 = '?module=mno&action=pqr';
        const RES = await fetch(URL1);
        let output = await RES.json();
   },
   error: function (e) {
     alert('error ' + e.message);
   },
   // Form data
   data: formData,
   type: 'POST',
   //Options to tell jQuery not to process data or worry about content-type.
   cache: false,
   contentType: false,
   processData: false
});

不知道我哪里错了。

【问题讨论】:

  • 不工作是什么意思?您将fetch(URL1) 返回的promise 的解析器值分配给RES,但随后不对其进行任何操作。你期望发生什么?
  • @Utkanos 我在问题中添加了let output = await RES.json(); 声明。问题是代码没有跨越const RES 语句。
  • 你是如何确定这个事实的?
  • @Utkanos 我正在获取fetch(URL1) 的查询没有执行。

标签: jquery ajax asynchronous async-await


【解决方案1】:

好的,知道了,我刚刚从success 中删除了代码并添加了一个新的function,它就成功了。

$.ajax({
   url: '?module=abc&action=xyz',
   //Ajax events
   beforeSend: function (e) {
     //
   },
   success: async function (e) {
       //I added the below 'runquery()' function.
       runquery();
   },
   error: function (e) {
     alert('error ' + e.message);
   },
   // Form data
   data: formData,
   type: 'POST',
   //Options to tell jQuery not to process data or worry about content-type.
   cache: false,
   contentType: false,
   processData: false
});

然后又添加了一个新的function

async function runquery() {   
    const URL1 = '?module=mno&action=pqr';
    const RES = await fetch(URL1);
    let output = await RES.json();
 }

【讨论】:

    猜你喜欢
    • 2021-08-03
    • 2012-11-28
    • 2012-06-29
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多