get returned values from jquery get?

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-30 20:33:52

问题


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 firstid;
        var nextid;

    $.get(callUrl, function(data) {  // call to add node
         var n = data.indexOf("id-");
         var m = data.indexOf("id-");
         firstid = data.substr(n+3,m - (n+3));
         nextid = data.substr(m+3);

             alert("firstid:" + firstid);  // returns correct value
    });

        alert("firstid:" + firstid);  // returns undefined for firstid

how can I get firstid outside the function?


回答1:


ALL AJAX CALLS ARE ASYNCHRONOUS

SO you need to use callbacks. anything outside that will return undefined.

$.get(callUrl, function(data) {  // call to add node
     var n = data.indexOf("id-");
     var m = data.indexOf("id-");
     firstid = data.substr(n+3,m - (n+3));
     nextid = data.substr(m+3);

     doSomethingWithFirst(firstid);
});

function doSomethingWithFirst(f)   {
     //NOW do something
}



回答2:


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.




回答3:


This is because it is done asynchronous (one of the basic principles of AJAX). You can set async to false or use some other callback construction to use your value returned from the get call.



来源:https://stackoverflow.com/questions/11156852/get-returned-values-from-jquery-get

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!