gpt4 book ai didi

jquery - 使用Defferred.then()将一些已解决的案例过滤为拒绝的案例

转载 作者:行者123 更新时间:2023-12-01 08:09:17 25 4
gpt4 key购买 nike

我正在执行一个 ajax 调用,它可以返回 {status: ok}{status: error} 以及其他数据。

我想做一个 .then(doneFilter) 来检查 status 成员,然后修改一些内容,以便仅当状态为 Deferred 时才会解析没问题。

我不确定其语法。有人可以给我写一个例子吗?

最佳答案

这是一个典型的例子:

/*  Returns a deferred object.  It is resolved if the ajax call succeeded, and
is rejected otherwise.
*/
function doAjaxThing() {
var df = $.Deferred();
$.ajax('http://someurl.org/path/whatever').done( function(data) {
if('test for success here')
df.resolve();
else
df.reject();
}).fail( function() {
df.reject();
});

return df;
}

doAjaxThing().then(
function() { 'success!'; },
function() { 'failure.'; }
);

重要的是,您不仅要处理成功案例,还要处理失败案例。您的 ajax 调用有两种失败的可能:请求返回 {status: error} 或请求本身由于某种服务器错误而失败。

您还有其他选择。您可以将解析/拒绝调用中的数据传递给处理程序。您还可以使用 acceptWith()rejectWith() 将上下文(this 对象)传递给您的处理程序。

我建议您阅读deferred object documentation如果您还没有的话。

关于jquery - 使用Defferred.then()将一些已解决的案例过滤为拒绝的案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14609539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com