Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 函数内容执行不正常_Javascript_Jquery_Dom - Fatal编程技术网

Javascript 函数内容执行不正常

Javascript 函数内容执行不正常,javascript,jquery,dom,Javascript,Jquery,Dom,我有一个java脚本函数 function myfunction() { var url = location.href; var ajaxRespose; $.ajax({ type:"GET", url: url, cache:false, dataType: "text", success: function(response) {

我有一个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)上,我得到:

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

,因为AJAX是异步的(因此得名)。记录“first ajaxRespose”的控制台日志是在AJAX请求完成之前执行的,这就是为什么没有定义。然后AJAX请求完成并得到响应。

因为AJAX是异步的(因此得名)。记录“first ajaxRespose”的控制台日志是在AJAX请求完成之前执行的,这就是为什么没有定义。然后AJAX请求完成并获得响应。

因为
$.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(...);   // 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调用时,其他代码将并行执行。。。使其工作的唯一方法是在ajax的回调函数中定义它。回调函数在ajax调用完成时执行,从而在其中获得ajaxRespose,这是因为ajax是异步的。…并行工作。。。因此,在执行Ajax调用时,其他代码将并行执行。。。使其工作的唯一方法是在ajax的回调函数中定义它。回调函数在ajax调用完成时执行,从而在其中获得ajaxRespose

替换
数据类型:“text”,
数据类型:“json”,
异步请求就是这样工作的,第一次调试是在ajax请求完成之前执行的。可能重复的Replace
dataType:“text”,
dataType:“json”,
这就是异步请求的工作方式,第一次调试是在ajax请求完成之前执行的。可能重复的感谢,我添加了“async:false”现在我得到的输出是:ajaxrepose==>:[object object]first ajaxrepose:[object object]嘿,每个人都要做一个好的支持者,对(好的或坏的)答案或评论进行投票。谢谢,我添加了“async:false”,现在我得到的输出是:ajaxrepose=>:[object object]first ajaxrepose:[object]大家好,请做一个好的支持者,投票给(好的或坏的)答案或评论。