函数内容执行顺序不对

function contents execution not in order

本文关键字:顺序 执行 函数      更新时间:2023-09-26

我有一个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;
}

在我的控制台(firbug)我得到:

first ajaxRespose: undefined
ajaxRespose ==>:[object Object]

我的问题是,为什么ajax调用在"第一次"console.debug之后执行。PS:我已经简化了函数,(函数工作正常,但问题是在执行顺序)

由于$.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]

因为AJAX是异步的(因此得名)。在AJAX请求完成之前,记录"first ajaxresponse"的控制台日志正在执行,这就是为什么未定义。然后AJAX请求完成,您得到响应。

这是因为Ajax是异步的....工作发生在"并行"…所以当你的Ajax调用被执行时,其他代码被并行执行…使其工作的唯一方法是在ajax的回调函数中定义它。回调函数在ajax调用完成时执行,从而在其中获得ajaxresponse