2014-09-26 47 views
0

我有三个元素的html窗体 - 按钮启动和停止和文本区域。一旦按下开始按钮,我想要执行多个ajax请求,并且一旦接收到更新文本区域的结果,一旦停止被按下,应该停止处理ajax请求。如何在后台执行ajax请求和html元素更新?

我试图做类似如下:

$(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'); 
     }); 
    } 
    }); 

但预期它不工作 - 浏览器选项卡挂起。我的代码有什么问题?

+0

'而(INPROGRESS)'永不停止。你需要'轮询'inProgress'变化! – loveNoHate 2014-09-26 13:28:00

+0

您的浏览器卡在永无止境的循环中 – 2014-09-26 13:28:03

+0

您的实际需求是什么? – 2014-09-26 13:30:16

回答

1

不要使用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(); 
}); 
1

好吧,既然$就默认是异步的,你这是XHR(AJAX调用)的loooot! ;-)

试试这个:

$(document).ready(function(){ 
    var inProgress = false; 

    $("#stop").click(function() { 
    inProgress = false; 
    }); 

    $("#start").click(function() { 
    inProgress = true; 
    refresh(); 
    }); 

    function refresh() {  
     $('#textarea').html($('#textarea').val()+sometext+'\n'); 
     $.ajax({url: 'http://example.com'}) 
      .done(function(data, textStatus, jqXHR) { 
      $('#textarea').html($('#textarea').val()+someresult+'\n'); 
      if (inProgress) refresh(); 
      }); 
    } 
}); 
0

大概是因为浏览器正在忙于处理请求,它可以不听其他事件。尝试将代码放入函数中,然后使用合理的超时时间,然后使用

setTimeout(function_reference, timeoutMillis); 

见该代码作为一个例子:

function startTime() { 
    var today = new Date(); 
    var h = today.getHours(); 
    var m = today.getMinutes(); 
    var s = today.getSeconds(); 
    // add a zero in front of numbers<10 
    m = checkTime(m); 
    s = checkTime(s); 
    document.getElementById("txt").innerHTML = h+ ":" + m + ":" + s; 
    t = setTimeout(function(){startTime()}, 500); 
} 

function checkTime(i) { 
    if (i<10) { 
     i = "0" + i; 
    } 
    return i; 
}