简体   繁体   中英

Return value from js enclosing function in ajax

How can I return value from enclosing js function? I've tried next example, but it doesn't work(it returns me:

function executeCommand(data, func){                
$.ajax({
type: 'POST',
url: SERVERPATH+'Commands/',
data: data,
success: func,
dataType: 'json'
});     
}

function executeServiceOperation(data){
var result = null;
executeCommand(data,
result = (function(data,status){        
      if( status=='success' ){                                  
        return data.result;     
      }
      else return null;          
    })(data,status)
);
 return result; 
}

result is null everytime. I think it happen because of status . How can I get status variable? Thanks.

Acording to your code, you must pass a function in the second parameter but you are returning an assignment (which is equivalent "true"). It will fail.

instead, do something like this:

executeCommand(data, function(data,status){ //function as second parameter       
    if( status=='success' ){                                  
       return data.result;     
    } else {
       return null;  
    }        
});

However, it's still wrong. Anything involving AJAX is anynchronous. Thus you can't "return" anything from it. What you should do is pass a callback when something "successful" happens.

function executeServiceOperation(data, callbacks){

    //do some set-up stuff you want

    executeCommand(data,function(data,status){        
        if( status === 'success'){                              
            callbacks.success(data.result) //execute callback with result
        } else {
            callbacks.fail(null);     //execute fail callback, with null if necessary
        }          
    });
);

executeServiceOperation(data, {
    success :function(result){
        //do something with result
    },
    fail : function(){
        //do something as if it returned null
    }
});

this code above is written in the traditional callback fashion. you should take a look at Deferred Objects for "sugary" code.

It's not possible to return the data you get from the ajax function. In stead you must assign a function which will be called after the ajax function has succeeded.

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