Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

javascript - Return callback value outside callback function (ajax)

I am trying return callback value outside callback function example:

I make the function based in topic: How do I return the response from an asynchronous call?

(function (){

    return getAjaxResult(function(result) { return result; }); 
     //<-- Return Undefined (in console log return correct value)
})();

function getAjaxResult(callback){
    $.ajax({
       url: 'myurl',
       type: 'GET',
        success: function (result) 
        {
           if (result === 'working'){
                callback(result);
          }else if (result === 'notworking'){
                callback('notworking');
          }
        }
      })
 }

Return "Undefined" (in console log return correct value).

I do not know if this is the best option to return an ajax value in callback

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two ways to do this, you can use async false but is deprecated and you can always use a promise:

do a function like this:

function ajaxCallback(id){
  return   $.ajax({
    method: "POST",
    url: "../YourUrl",
    data: {  id: id}
  })
}

then call it like this:

if (id != '')//
{
    ajaxCallback(id)
               .done(function( response ) {
                               //do something with your response
                            });
}

Hope it helps


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...