Javascript - local scope objects not accessible from nested function

大兔子大兔子 提交于 2019-12-04 17:28:19

The A in Ajax is an important part of the acronym. Asynchronous JavaScript and XML is asynchronous.

$.ajax({success:someFunction}) means Make an HTTP request and when the response arrives, run someFunction

return ganttObject runs before the response arrives.

You should do anything you want to do with the data inside someFunction and not try to return data to the calling function.

The A in AJAX stands for asynchronous. So the call immediately returns and as soon as it finishes, the success callback is called.

So, simply change your code to use a callback:

function getGantt(requestNumber, callback) {
    var ganttObject;
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: "get_gantt.php",
        data: {request_number: requestNumber},
        success: function(returnValue){
            callback(returnValue);
        }
    });
}

$(function() {

    var requestNumber = $('#request_number').text();

    var ganttObject = getGantt(requestNumber, function(ganttObject) {
        console.log(ganttObject);
    });

});

Btw, I've also removed this parseJSON stuff - setting dataType to json does the job and is less dirty.

I know why it's not returning it at least. The ganttObject may be in the same scope, but the success function is ultimately running in the readyState callback from the XMLHTTP object, so it's on a different thread than the getGantt function. Can you make the $(function(){... code apart of your success function?

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