weixin_33704591 2014-08-07 02:27 采纳率: 0%
浏览 35

Ajax中的javascript范围

How do I access variables outside the ajax call?

    var times;
    for(var i = 0; i < 5; i++)
    {
        var sendDate = (new Date()).getTime();
        $.ajax({
            //type: "GET", //with response body
            type: "HEAD", //only headers
            url: "del.php",
            success: function()
            {
                var receiveDate = (new Date()).getTime();
                var responseTimeMs = receiveDate - sendDate;
                times.push(responseTimeMs);
            }
        });
        times[4]; //undefined
    }

Where I call times[4] is undefined. I think because it is out of scope. How do I access the same times that was in the success function?

  • 写回答

1条回答 默认 最新

  • weixin_33690963 2014-08-07 02:38
    关注

    Value of times[4] will be undefined because Ajax is an asynchronous call and it will be executed separately, and when you access times[4] at that time success function isn't called as Ajax call won't be completed or will be in progress.

    Write you logic of processing data received via Ajax call in only Success function or create a separate method and call it in success method

    var times;
    for(var i = 0; i < 5; i++)
    {
        var sendDate = (new Date()).getTime();
        $.ajax({
            //type: "GET", //with response body
            type: "HEAD", //only headers
            url: "del.php",
            success: function()
            {
                var receiveDate = (new Date()).getTime();
                var responseTimeMs = receiveDate - sendDate;
                times.push(responseTimeMs);
                //Write here the logic of processing data
                // received from server
            }
        });
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 jetson nano
  • ¥15 :app:debugCompileClasspath'.
  • ¥15 windows c++内嵌qt出现数据转换问题。
  • ¥20 公众号如何实现点击超链接后自动发送文字
  • ¥15 用php隐藏类名和增加类名
  • ¥15 算法设计与分析课程的提问
  • ¥15 用MATLAB汇总拟合图
  • ¥15 智能除草机器人方案设计
  • ¥15 对接wps协作接口实现消息发送
  • ¥15 SQLite 出现“Database is locked” 如何解决?