duanhan5230 2011-05-22 22:35
浏览 99

AJAX:在循环中发送xmlhttp请求

I have this function below and I call that function in a loop I get the alert n times but only n-1 or sometimes n-2 responses

if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        alert(xmlhttp.responseText);
        //document.getElementById("warnings_panel").innerHTML+=xmlhttp.responseText;
    }
}

alert("in ajax) 

xmlhttp.open("GET","getresponse.php?start="+ start + "&end=" + end,true);
xmlhttp.send();
  • 写回答

3条回答 默认 最新

  • duandan1995 2011-05-22 22:48
    关注

    onreadystatechange gets terminated when your function ends because the xmlhttp object gets removed as it is not a global variable. Am I right?

    Better would be to put only the AJAX request in a function, so that the xmlhttp object is only created once (I used a shorter version to create the xmlhttp object in this example).

    var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
    
    function request() {
        xmlhttp.open('GET', 'getresponse.php?start=' + start + '&end=' + end, true);
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                alert(xmlhttp.responseText);
            }
        }
        xmlhttp.send(null);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂