Javascript - local scope objects not accessible from nested function

六月ゝ 毕业季﹏ 提交于 2019-12-21 21:38:28

问题


I am trying to have a function grab an object from a php file on another page. I'm using the jQuery ajax function to to do the json grab, which is working correctly. The issue is when I try to return that object from the function.

The first time I log the object (from within the success function) it is correct in the console, but the returned object from the function getGantt() logs as "undefined".

How do I get this object out of the function?

My code:

    function getGantt(requestNumber){
        var ganttObject;
        $.ajax({
               type: "POST",
               url: "get_gantt.php",
               data: {request_number: requestNumber},
               success: function(returnValue){
                     ganttObject = $.parseJSON(returnValue);
                    console.log(ganttObject); //this logs a correct object in the console

                }
        });
        return ganttObject;
    }

    $(function(){ //document ready function

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

        var ganttObject = getGantt(requestNumber);
        console.log(ganttObject); //this logs "undefined"

    }); //end document ready function

回答1:


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.




回答2:


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.




回答3:


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?



来源:https://stackoverflow.com/questions/4891491/javascript-local-scope-objects-not-accessible-from-nested-function

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