Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

jquery - Javascript callback functions with ajax

I am writing a generic function that will be reused in multiple places in my script.

The function uses ajax (using jQuery library) so I want to somehow pass in a function (or lines of code) into this function to execute when ajax is complete. I believe this needs to be a callback function, but after reading through a few callback answers I'm still a bit confused about how I would implement in my case.

My current function is:

function getNewENumber(parentENumber){

        $.ajax({
               type: "POST",
               url: "get_new_e_number.php",
               data: {project_number: projectNumber, parent_number: parentENumber},
               success: function(returnValue){
                    console.log(returnValue);
                    return returnValue; //with return value excecute code

                },
                error: function(request,error) {
                    alert('An error occurred attempting to get new e-number');
                    // console.log(request, error);
                }
        });
    }

With this function I want to be able to do something in the same way other jQuery functions work ie;

var parentENumber = E1-3;

getNewENumber(parentENumber, function(){
    alert(//the number that is returned by getNewENumber);
});
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Just give getNewENumber another parameter for the function, then use that as the callback.

   // receive a function -----------------v
function getNewENumber( parentENumber, cb_func ){

    $.ajax({
           type: "POST",
           url: "get_new_e_number.php",
           data: {project_number: projectNumber, parent_number: parentENumber},

             // ------v-------use it as the callback function
           success: cb_func,
            error: function(request,error) {
                alert('An error occurred attempting to get new e-number');
                // console.log(request, error);
            }
    });
}

var parentENumber = E1-3;

getNewENumber(parentENumber, function( returnValue ){
    alert( returnValue );
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...