Scope variable in ajax call

前端 未结 3 1325
一生所求
一生所求 2021-01-14 17:57

Why the final console log is undefined?Variable time has a global scope and ajax call is async.

This is my code:

var time;
$.ajax({
    async: false,         


        
3条回答
  •  庸人自扰
    2021-01-14 18:30

    OK, a bit contrived, but I hope it shows the point regarding scope of time and timing ...

    $.ajax({
        async: false,
        dataType: 'jsonp',
        type: 'GET',
        url: "http://www.timeapi.org/utc/now.json",
        success: function (data) {
            console.log(data.dateString);
            time = data.dateString;
        },
        error: function (data) {
            console.log("ko");
        }
    });
    
    window.setTimeout("console.log('time: '+time)",3000);
    

    JSfiddle

提交回复
热议问题