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
            }
        });
    
    }
    
    评论

报告相同问题?