我发现这段代码可以满足我的要求:
var promise = this.model.save();
$.when(promise).then(function() {
console.log(promise.responseText);
});
我想取回
responseText
从我的 Backbone 电话到 this.model.save()
.此代码已记录在 here .但它不会记录任何内容,即使我在 console.log()
中提取原始文本字符串也是如此。称呼。有人可以用外行的术语解释什么是 jQuery promise 吗?我读过它们,但我不认为我完全明白它们是什么。这可能有助于我理解为什么这段代码对我不起作用。如果我
console.log(promise)
在第一行和第二行代码之间,我得到 responseText
.因此,$.when
中发生了一些事情。或 then
这导致出错。编辑:
阅读文章后,我发现我可以这样做:
var promise = this.model.save();
$.when(promise).then(null, function(obj) {
console.log(obj.responseText);
});
但我不明白
null
是什么代表。 then
似乎需要两个参数,一个成功函数和一个失败函数。但是成功功能不就是第一吗?我从服务器收到 200 响应。
最佳答案
所以首先,我很确定你不需要 when
部分;来自 jQuery 文档:
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information).
由于 Promise 有
then
方法已经,你可以这样做:this.model.save().then(null, function(obj) {
console.log(obj.responseText);
});
(至少对我来说,上面的代码读起来几乎像一个英文句子,这是使用 Deferreds 的一个主要优势。)
至于你的
null
论点,文档再次非常清楚。 then
共有三个签名(这只是为了涵盖不同的 jQuery 版本;任何给定的版本都更少):deferred.then( doneFilter [, failFilter ] [, progressFilter ] )
deferred.then( doneCallbacks, failCallbacks )
deferred.then( doneCallbacks, failCallbacks [, progressCallbacks ] )
如您所见,所有三个都首先采用“完成”功能,其次是失败功能。这似乎确实意味着您遇到了失败,这令人困惑。避免该问题的一种方法是不使用
then
一点也不。相反,请尝试以下操作:this.model.save().always(function(obj) {
console.log(obj.responseText);
});
无论发生什么,这都会使您的函数被调用。但是,您可能应该弄清楚发生了什么,因此您可能想要添加一个成功和失败回调来进行一些调试:
this.model.save().done(function() {
// Success case
}).fail(function() {
// Failure case
});
关于backbone.js - jQuery Promise 和 Backbone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14407294/