嵌套 JSON GET 函数
我正在寻找一种方法来拥有 .getJSON,调用另一个函数,该函数反过来进行另一个 .getJSON 调用。
我在控制器上迭代调用 JSON 方法,并希望在满足特定条件时完成此迭代周期。如果满足此条件(只能从 JSON 方法中检查),我想在控制器上调用另一个 JSON 方法(保留一些数据等)。
但是,第二个 JSON 调用从未进行。当我在第一个函数之外手动调用第二个函数时,调用是正确的。
有什么暗示吗?还是我的设计完全有缺陷?
编辑
Chyeaah..忘记了代码..:D
<script type="text/javascript">
$(window).load(function() {
var poller = setInterval(tick, 1000);
});
function tick() {
$.getJSON("votingtick", function(voting) {
if (voting != null) {
if (voting.timeleft < 0) {
clearInterval(poller);
finalize();
} else {
$("#timeout").text(voting.timeleft);
$("#voters").text(voting.votingCount);
}
}
});
}
function finalize() {
$.getJSON("votingend", function(voting) {
if (voting != null) {
$("#finished").fadeIn('fast');
}
});
}
</script>
认为这是最相关的,不是吗?
I am looking for a way to have a .getJSON, call another function which in return conducts another .getJSON call.
I'm iteratively calling a JSON method on my Controller and want to finish this iterative cycle if a certain condition is met. If this condition is met (can only be checked from within the JSON method), I want to call another JSON method on the Controller (persisting some data etc.).
However, the second JSON call is never made. When I'm callin the second function manually outside of the first function, the call is made correctly.
Any hints on that or is my design utterly flawed anyways?
EDIT
Chyeaah.. forgot the code.. :D
<script type="text/javascript">
$(window).load(function() {
var poller = setInterval(tick, 1000);
});
function tick() {
$.getJSON("votingtick", function(voting) {
if (voting != null) {
if (voting.timeleft < 0) {
clearInterval(poller);
finalize();
} else {
$("#timeout").text(voting.timeleft);
$("#voters").text(voting.votingCount);
}
}
});
}
function finalize() {
$.getJSON("votingend", function(voting) {
if (voting != null) {
$("#finished").fadeIn('fast');
}
});
}
</script>
Think this is most relevant, no?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我怀疑您的轮询器变量存在范围问题。它可能只在您的 $(window).load 函数中定义,而没有在其他地方定义。因此,当浏览器尝试执行
clearInterval
时,会引发异常并中止脚本。您可以通过使用 try catch 包围$.getJSON
函数中的代码来验证这一点。如果删除该函数中的 var 关键字, poller 将成为一个全局变量,您可以在脚本中的任何位置引用它。
I suspect that you have a scope problem with your poller variable. It is probably only defined in your
$(window).load
function and nowhere else. So when the browser attempts to execute theclearInterval
, an exception is thrown and the script is aborted. You can verify this by surrounding the code in your$.getJSON
function with a try catch.If you remove the var keyword in that function, poller will become a global variable that you can reference anywhere in the script.
这可能是因为当您使用未定义的值调用
clearInterval
时收到错误。您在load
事件处理程序中本地声明变量poller
,因此它在外部未定义。在函数外部声明它:
It's probably because you get an error when you call
clearInterval
with an undefined value. You declare the variablepoller
locally in theload
event handler, so it's undefined outside it.Declare it outside the function: