简体   繁体   中英

Return result from AJAX

I want to return response data when XMLHttpRequest transaction completes successfully. upon calling my function trashAnswer() to a variable I expect to assign the value returned to the variable and do something with it like below:

I can see resData is always undefined when i try to access data from it. Please how can I solve this?

var resData = trashAnswer({answerid:58,answererid:65,questionid:458});

This is the code:

//This function will trash answer object
function trashAnswer(param){
    if (typeof param !== 'object' || param == null ) {
        throw "trashAnswer(): Strictly expect valid object.";
    }

    var param = $.extend({answerid:0,answererid:0},param),
            fd    = new FormData();
                            fd.append('answerData',JSON.stringify(param));
                            fd.append('trash-answer',true);

    var req = AJAX_REQEUST_OB();
    req.open(bigPipe.formMethod.a,ajax.ac,true);
    req.onload = function(){
        if (req.readyState === req.DONE && req.status === 200) {
           //ParseJSON is a custom function to check if response is a valid JSON...if its valid then then function will return response Data else return false
            var Data = ParseJSON(req.responseText); 
            //process data...
            var EvalData = !Data ? function(){
                throw "Invalid JSON";
            }:function(Data){
                //do something...
                return Data;
            };
            //call EvalData ****method
            EvalData(Data);
        }

    }

    //send request.
    req.send(fd);
}

This is an asynchronous call. When you do trashAnswer({...}); you are triggering the request and your code continues to execute. At some point in the future your request may work. Here the "may" part is important: your request may fail for several reasons, but you are only checking the HTTP status 200, that is an "OK" response).

An easy solution:

var resData;
trashAnswer({answerid:58,answererid:65,questionid:458});

//This function will trash answer object
function trashAnswer(param){
    // ...
    req.onload = function(){
        if (req.readyState === req.DONE && req.status === 200) {
            // ...
            // in your "//do something...":
            resData = // your result here. If you do not have a local variable,
                      // it will change the global one (not recommended, see comment below)
        }
    }
    // ...
}

Your solution is even better if you avoid using a global variable ( See here why ). But I believe this is a good starting point for you to understand how async calls work.

You can also use promises (including the async/await syntax). A good start reading about how this works is https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM