【发布时间】:2015-02-11 14:03:16
【问题描述】:
我正在尝试使用 jQuery 的 AJAX deferreds 来返回一个可以解析和使用的 JSON 字符串,但我已经将自己编码到一个角落并且可能搞砸了逻辑。我希望 AJAX 调用的结果会在 .done() 回调中返回,它们是。我认为一旦完成,我可以返回结果以用于函数的其余部分。我知道我遗漏了一些非常明显和简单的东西,我无法确定它是什么。
这是函数的初始编码,仍然非常处于测试模式。 JSON 在.done() 函数中正确返回,但我无法将其分配到函数之外以供使用。
checkUserRoles = function(){
var userRole, foo, roles, i$, len$, i;
userRole = roleChecker();
foo = userRole.done(function(data){
var bar;
bar = foo.responseText; // correctly returns the JSON data
console.log(bar);
return bar; // is undefined, this is the problem
});
if (userRole !== false) {
userRole = jsonDecode(userRole);
} else {
userRole = "";
}
roles = userRole.split(',');
$("if-user-role").hide();
for (i$ = 0, len$ = roles.length; i$ < len$; ++i$) {
i = roles[i$];
$("if-user-role[data-role~=" + i + "]").show();
}
return true;
};
this.roleChecker = function(){
var retVal, allCookies, i$, len$, thecookie, hashedCookie, theHash, userHash, post;
retVal = "";
allCookies = document.cookie.split(';');
for (i$ = 0, len$ = allCookies.length; i$ < len$; ++i$) {
thecookie = allCookies[i$];
if (thecookie.indexOf('userHash') >= 0) {
hashedCookie = thecookie;
theHash = hashedCookie.split('=');
userHash = theHash[1];
}
}
post = $.ajax({
url: '/services/check_hash.php',
data: {
hash: userHash
},
type: "POST"
});
return post;
};
您在此处看到的代码是我们广泛使用的 LiveScript 编译的输出。我不认为 LiveScript 对最终结果有影响,我只需要做很多事情才能得到我期望的正确的 JavaScript / jQuery 输出。
注意:因为这或多或少是代码 foo 的第一次传递,因此不会传递到后续 if 语句,因为 userRole 最初是硬编码的在尝试使函数更具动态性之前进行测试。
如何返回foo.responseText 或bar 以供后续程序使用?我是否需要在.done() 函数中以if 条件开头的过程?
【问题讨论】:
-
赞成承认您使用不正确并且没有说它没有按应有的方式工作
-
不知道为什么我的近距离投票被删除了,但这是重复的:stackoverflow.com/questions/14220321/…
标签: javascript jquery promise deferred