函数内容执行不按顺序

时间:2013-04-02 09:17:13

标签: javascript jquery dom

我有一个java脚本函数

function myfunction() {

    var url = location.href;
    var ajaxRespose;

        $.ajax({
            type:"GET",
            url: url,
            cache:false,
            dataType: "text",
            success: function(response) {
                var data = $.parseJSON(response);
                ajaxRespose = data;
                console.debug("ajaxRespose ==>:"+ajaxRespose);
            }
        });
        console.debug("first ajaxRespose: " +ajaxRespose);
    }
    return false;
}

在我的控制台(冷冻)我得到:

first ajaxRespose: undefined

ajaxRespose ==>:[object Object]

我的问题是,为什么ajax调用在“first”console.debug之后执行。 PS:我已经简化了这个功能,(功能正常,但问题是执行顺序)

3 个答案:

答案 0 :(得分:1)

因为AJAX是异步的(因此名称)。记录“第一个ajaxRespose”的控制台日志正在AJAX请求完成之前执行,这就是你未定义的原因。然后AJAX请求完成,您就会得到响应。

答案 1 :(得分:1)

由于$.ajax() 异步,事件序列如下所示:

$.ajax(...);   // executes AJAX request
console.debug("first ajaxResponse:" + ajaxRespose);   // undefined

/* some time later, we receive AJAX response */

// it executes the success function from the original AJAX request
console.debug("ajaxRespose ==>:"+ajaxRespose);  // [object Object]

答案 2 :(得分:1)

这是因为Ajax是Asynchronus .... 工作“并行”。 ..所以当你的Ajax调用被执行时,其他代码并行执行...唯一的方法使其工作的是在ajax.callback函数的回调函数内定义它,当ajax调用完成时执行,从而获得ajaxRespose

相关问题