Scope variable in ajax call

前端 未结 3 1293
一生所求
一生所求 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:26

    Change async to the boolean false.

    http://api.jquery.com/jQuery.ajax/

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

    Also, note that if you need to use dataType: 'jsonp' here for cross-domain, you won't be able to synchronize -- so use a promise.

    var time;
    $.ajax({
        dataType: 'jsonp',
        type: 'GET',
        url: "http://www.timeapi.org/utc/now.json",
        success: function (data) {
            time = data;
        },
        error: function (data) {
            console.log("ko");
        }
    })
    .then(function(){ // use a promise to make sure we synchronize off the jsonp
        console.log(time);    
    });
    

    See an example like this here using Q.js:

    DEMO

    0 讨论(0)
  • 2021-01-14 18:28

    In your code, you initialize the global variable 'time' as 'data'. Where does this data variable come from? If the data variable is not global also, when you try to use console.log(time); , it may be undefined because the data variable is undefined.

    Make sure both variables are within scope to be used globally. That might work. Good luck!

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题