我有三个元素的html表单-按钮的开始和停止以及文本区域。一旦按下开始按钮,我想执行多个ajax请求,并且一旦收到结果以更新文本区域,一旦按下stop,就应该停止处理ajax请求。
我试图做如下的事情:
$(document).ready(function(){
var inProgress = false;
$("#stop").click(function() {
inProgress = false;
});
$("#start").click(function() {
inProgress = true;
while (inProgress) {
$('#textarea').html($('#textarea').val()+sometext+'\n');
$.ajax({url: 'http://example.com'})
.done(function(data, textStatus, jqXHR) {
$('#textarea').html($('#textarea').val()+someresult+'\n');
});
}
});
但这并不能按预期工作-浏览器选项卡挂起。我的代码有什么问题?
最佳答案
不要使用while循环。您应该以异步方式执行此操作:在.done函数的末尾,放置另一个异步ajax调用。
// other stuff goes here
function doRequest() {
$.ajax({url: 'http://example.com'})
.done(function(data, textStatus, jqXHR) {
$('#textarea').html($('#textarea').val()+someresult+'\n');
if (inProgress) doRequest();
});
}
$("#start").click(function() {
inProgress = true;
$('#textarea').html($('#textarea').val()+sometext+'\n');
doRequest();
});