get returned values from jquery get?

前端 未结 3 1505
时光取名叫无心
时光取名叫无心 2021-01-07 10:27

I am making jquery calls to get and getJSON, but cannot access returned values outside of callback function. How can I access the returned data?

        var          


        
3条回答
  •  爱一瞬间的悲伤
    2021-01-07 10:58

    The second alert("firstid:" + firstid); returns undefined because at the moment of execution it is in fact undefined.

    The first alert("firstid:" + firstid); returns the expected result as it fires after the $.get is finished getting.

    AJAX - Stands for Asynchronous JavaScript and XML. Asynchronous events are those occurring independently of the main program flow. While you can set the request to synchronous it is not recommended.

    If you wrapped your second alert("firstid:" + firstid); in a timeout with a 5 second delay it would display the expected result.

    setTimeout(function() { alert("firstid:" + firstid); }, 5000);
    

    Or you could wrap your second alert("firstid:" + firstid); in an interval with a 1 second delay it would eventually display the expected result.

    var callback_interval = setInterval(function() {
        if(typeof(firstid) == 'undefined') return;
        clearInterval(callback_interval);
        alert("firstid:" + firstid);
    }, 1000);
    

    But it's best to work with the variables directly in the $.get success callback or via function calls within that success callback.

提交回复
热议问题