Javascript 带有 ES6 Promise 的 jQuery ajax

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35135110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:18:10  来源:igfitidea点击:

jQuery ajax with ES6 Promises

javascriptjqueryajaxcorses6-promise

提问by Chad Befus

I am trying to make a post request via jQuery using an ES6 promise:

我正在尝试使用 ES6 承诺通过 jQuery 发出发布请求:

I have a function:

我有一个功能:

getPostPromise(something, anotherthing) {
  return new Promise(function(resolve, reject) {
    $.ajax({
      url: someURL,
      type: 'post',
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(
        something: something,
        anotherthing: anotherthing
      }),
      dataType: 'json',
      success: resolve,
      error: reject
    });
  });
}

and I call it like so:

我这样称呼它:

getPostPromise(
  'someFooStuff',
  'someBarStuff'
).then(
  function(returnedData) {
    console.log("Good: ", returnedData);
  },
  function(responseObject) {
    console.log("Bad: ", responseObject);
  }
).catch(
  function(errorThrown) {
    console.log("Exception: ", errorThrown);
  }
);

My server is returning a response as expected with the request body being in JSON format but my console output is:

我的服务器按预期返回响应,请求正文为 JSON 格式,但我的控制台输出是:

Good: undefined

好:未定义

Why am I not getting the returned data?

为什么我没有得到返回的数据?

Thanks to anyone/everyone for any help.

感谢任何人/所有人的帮助。

--- UPDATE EDIT ---

--- 更新编辑 ---

I have reduced my js to only:

我已经将我的 js 减少到只有:

import $ from 'jquery';
$.get('http://localhost:8008/api/user')
  .done(function(data) {
    console.log(data);
  });

I still get undefined as output. If I open up the request in the network tab I can see the response object with the correct data. The request is made, my server is happy and responds, and the results are in my browser but the data parameter of done is undefined. I am stumped.

我仍然未定义为输出。如果我在网络选项卡中打开请求,我可以看到带有正确数据的响应对象。发出请求,我的服务器很高兴并做出响应,结果在我的浏览器中,但 done 的数据参数未定义。我难住了。

--- UPDATE 2 - SOLUTION FOUND ---

--- 更新 2 - 找到解决方案 ---

I discovered that the problem was with using: https://github.com/jpillora/xdomainto get around CORS. It would seem that that library screws up passing back values somehow. I have removed it and will implement CORS properly and to hell with browsers that don't support it.

我发现问题在于使用:https: //github.com/jpillora/xdomain来绕过 CORS。该库似乎以某种方式搞砸了传回值。我已经删除了它,并将正确实施 CORS,并让不支持它的浏览器见鬼去。

回答by Tomalak

jQuery Ajax methods return promises themselves, you don't needto wrap them at all.

jQuery Ajax 方法会自行返回承诺,您根本不需要包装它们。

But you can, of course, do it for consistency with the ES6 promise API.

但是,您当然可以这样做以与 ES6 承诺 API 保持一致。

UPDATEjQuery 3.0+ implements the Promise/A+ API, so there is no reason anymore to wrap anything in modern jQuery. Read up on the peculiarities of jQuery's promise implementation prior to version 3.0.

UPDATEjQuery 3.0+ 实现了 Promise/A+ API,所以没有理由再在现代 jQuery 中包装任何东西了。阅读jQuery 3.0 版之前的 promise 实现的特性

For jQuery versions before 3.0, I would decouple it more than you did:

对于 3.0 之前的 jQuery 版本,我会比你更多地解耦它:

function ajax(options) {
  return new Promise(function (resolve, reject) {
    $.ajax(options).done(resolve).fail(reject);
  });
}

and

ajax({
  url: someURL,
  type: 'post',
  contentType: 'application/json; charset=utf-8',
  data: JSON.stringify({
    something: something,
    anotherthing: anotherthing
  })
}).then(
  function fulfillHandler(data) {
    // ...
  },
  function rejectHandler(jqXHR, textStatus, errorThrown) {
    // ...
  }
).catch(function errorHandler(error) {
  // ...
});