我学习jQuery并且不了解这种情况:
在调试模式下运行此代码时,一切正常。但是当运行此代码正常时,calback函数不会启动。为什么? 在非调试模式下,我有 - > “开始” - > “结束10”
浏览器:谷歌浏览器。
var nrPost = 10;
$("#buttnX").click(function() {
alert("Start");
GoPosts();
End();
});
function End() {
alert('End ' + nrPost);
};
function GoPosts() {
$.ajaxSetup({async:false});
var url = "http://......";
var data = { ... };
$.post(url, data, Callback, 'json');
};
function Callback(response) {
if (response.error) {
return;
}
nrPost--;
if (nrPost > 0) [
GoPosts();
} else {
return;
}
};
答案 0 :(得分:3)
你有一个额外的};在你的代码中。我稍微改了一下,使用jQuery并把它放在jsfiddle上。
它应该提醒:“开始”然后“结束10”,根据你编写代码的方式这是正确的。你还有什么期待吗?
答案 1 :(得分:1)
我不知道你计划用递归实现做什么,但如果就是这样,你实际上可以这样做:
function startLoop(nrPost) {
// No need to put this in a loop
$.ajaxSetup({ async: false });
for (var i = 0; i < nrPost; i++) {
alert('Start ' + i);
var url = 'http://......';
var data = {};
$.post(url, data, function (response) {
if (response.error)
return;
alert('End ' + i);
}, 'json');
}
}
$('#buttnX').click(function () { startLoop(10) });
希望有所帮助!
答案 2 :(得分:0)
我想你期待显示器是:
这不太适合您的解决方案。
您的Ajax调用$.post(url, data, Callback, 'json');
是异步的。这意味着一旦$.post
方法返回,请求就会发送到您提供的URL。但是,在JQuery收到答案之前,不会调用Callback
。立即发生的是GoPosts
终止并且程序继续。它返回到代码的第5行,位于单击处理程序中的匿名函数内。此时,End()
被调用并警告“结束10”。
您可能希望将来电End
改为Callback
:
function Callback(response)
{
if (response.error)
{
return;
}
nrPost--;
if(nrPost>0)
GoPosts();
else
{
End(); // You only want to end once you have made you nrPost calls to GoPost
return;
}
};