Javascript 如何在后台进行ajax请求和html元素更新?
我有三个元素的html表单-按钮开始和停止以及文本区域。一旦按下开始按钮,我想执行多个ajax请求,一旦收到更新文本区域的结果,一旦按下停止按钮,ajax请求的处理应该停止 我试着做如下的事情:Javascript 如何在后台进行ajax请求和html元素更新?,javascript,jquery,ajax,asynchronous,Javascript,Jquery,Ajax,Asynchronous,我有三个元素的html表单-按钮开始和停止以及文本区域。一旦按下开始按钮,我想执行多个ajax请求,一旦收到更新文本区域的结果,一旦按下停止按钮,ajax请求的处理应该停止 我试着做如下的事情: $(document).ready(function(){ var inProgress = false; $("#stop").click(function() { inProgress = false; }); $("#start").click(function() {
$(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();
});
由于$.ajax在默认情况下是异步的,所以您正在进行XHR(ajax调用)!;-) 试试这个:
$(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();
});
}
});
可能是因为浏览器正忙于处理请求,无法侦听其他事件。尝试将代码放入函数中,然后使用
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;
}
函数开始时间(){
var today=新日期();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
//在数字前面添加一个零,而(inProgress)
从不停止。您需要对inProgress
更改进行轮询!您的浏览器陷入了永无止境的循环您的实际要求是什么?