从AJAX请求中获取价值

This used to be my code:

//At "click" I retrieve value from myFunctionA and use it in myFunctionB
$("#myButton").click(function()
{
    var response = myFunctionA();

    if(response) myFunctionB(response);
});

//Inside myFunctionA I perform an AJAX call (you will see it's really and "SJAX")
function myFunctionA()
{
    var response = myAjax();

    return response;
}

//This is not really and AJAX because of the async:false
function myAjax()
{
    var myJSON = {}

    $.ajax({
        url: "some_url.php",
        dataType: "json",
        async: false,
        error: function(jqXHR, textStatus, errorThrown)
        {
            alert(errorThrown);
        },
        success: function(data, textStatus, jqXHR)
        {
            myJSON = data;
        }
    });

    return myJSON;
}

The thing is that the above worked just fine. I request a value, wait for it, and then use it where I needed. Obviously that SJAX part shouldn't be done, I must do a real AJAX request. So while I was looking for a way to achive this I stumbled with questions like

jQuery: Return data after ajax call success

and really nice answers like

https://stackoverflow.com/a/14220323/702353

and also started to read about Deferred and methods like .done(). However I'm not being able to achieve the same result of my original SJAX code. So my questions are:

  • Is it possible to do what I want using an AJAX request?
  • Can it be done without modifying the .click() code?

Here is the current code I'm working on

$("#myButton").click(function()
{
    var response = myFunctionA();

    if(response) myFunctionB(response);
});

function myFunctionA()
{
    $.when(myAjax()).done(function(response)
    {
        return response;
    });
}

function myAjax()
{
    return $.ajax({
        url: "someurl.php",
        dataType: "json",
        error: function(jqXHR, textStatus, errorThrown)
        {
            alert(errorThrown);
        }
    });
}

Thanks for your time!

This is what needs to be done:

$("#myButton").click(function() 
{
    $.when(myFunctionA()).done(function(response)
    {
        myFunctionB(response);
    });    
});

function myFunctionA()
{
    var dfd = new jQuery.Deferred();

    $.when(myAjax()).done(function(data, textStatus, jqXHR)
    {
        dfd.resolve(data);
    });     

    return dfd.promise();    
}

function myAjax()
{
    return $.ajax({
        url: "someurl.php",
        dataType: "json",
        error: function(jqXHR, textStatus, errorThrown)
        {
            alert(errorThrown);
        },
        success: function(data, textStatus, jqXHR)
        {
            return data;
        }
    });
}

This answer on part 2 helped me a lot!