[英]jQuery .post doesn't return data in done and fail
I'm having trouble making a jQuery AJAX request and getting the data back in the .done and .fail methods. 我在发出jQuery AJAX请求以及在.done和.fail方法中获取数据时遇到麻烦。 Here is the code the calls the AJAX-requesting code:
这是调用AJAX请求代码的代码:
async function doSomething(){
const addressValid = await isAddressValid(form.address1.value, form.address2.value, form.city.value, form.state.value, form.zip.value);
if(!addressValid) return
}
And here's the request code: 这是请求代码:
export default (address1, address2, city, state, zip) => {
console.log(`Checking address`);
return $.post('/api/validate', {
address1,
address2,
city,
state,
zip
})
.done(function(data, status, xhr){
// Address is valid
return true;
})
.fail(function(jqXHR, textStatus, errorThrown ){
// Address is invalid or API is down, etc
return false;
});
}
My problem is that the return statements in the .done() and .fail() do not work. 我的问题是.done()和.fail()中的return语句不起作用。 After isAddressValid(), addressValid is either 'OK' if the address is good, or just nothing.
在isAddressValid()之后,如果地址正确,则addressValid为'OK',否则为空。 There's multiple problems with this - the first is that it disregards my
return true;
这有很多问题-首先是它无视我的
return true;
entirely. 完全。 The second is that when the address is invalid, the server returns a 400, and that returns nothing at all to addressValid.
第二个是,当地址无效时,服务器返回400,并且对addressValid完全不返回任何内容。
Per https://api.jquery.com/jquery.post/ : 每个https://api.jquery.com/jquery.post/ :
As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object.
从jQuery 1.5开始,所有jQuery的Ajax方法都返回XMLHTTPRequest对象的超集。 This jQuery XHR object, or "jqXHR," returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information).
$ .get()返回的此jQuery XHR对象或“ jqXHR”实现Promise接口,为其提供Promise的所有属性,方法和行为(有关更多信息,请参见Deferred对象)。
So it seems like what I'm doing should work. 所以看来我在做什么应该起作用。 I am thinking the promise will be resolved with my boolean return values, but it's not.
我认为诺言将用我的布尔返回值解决,但事实并非如此。 I've done this in the past with promises (not jQuery).
我过去曾做过Promise(不是jQuery)。 For example, use request-promise to request something, return the response and store it in a variable.
例如,使用request-promise请求某些内容,返回响应并将其存储在变量中。
Would appreciate any assistance. 不胜感激。
My guess is this is due to jQuery's promise-like jqXHR object. 我的猜测是这是由于jQuery的类似于 promise的jqXHR对象所致。
The await
keyword expects a promise and will use the standard then
(and maybe catch
) methods to determine the result. 关键字
await
期望一个诺言,并且将使用then
的标准方法(可能是catch
方法)来确定结果。
Try this instead 试试这个
return $.post(...).then(() => true, () => false)
Alternatively, use something other than jQuery that returns actual Promise
instances. 或者,使用jQuery以外的其他东西返回实际的
Promise
实例。 Even the native fetch
API may be better suited. 甚至本机
fetch
API可能更适合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.