简体   繁体   中英

Parametrizable success function for jQuery ajax call

I want to create a function to call the jQuery $.ajax function with a parameter that indicates the success function name that must be called after the success event.

Something like this, but I don't know how to fill the "complete" parameter, or even if it's possible to do this:

function callService(successFunctionName){
$.ajax({
 url: "serviceURL",
 type: "POST",
 data: "request",
 contentType: "text/xml; charset=\"utf-8\"",
 complete: successFunctionName
});

}

succesFunction1(){
}

successFunction2(){
}

Edit: I have to clarify that successFunctionName is an string

If successFunctionName is a string you could then use window[successFunctionName] . If it is the function itself it should work already

function callService(successFunctionName) {
    $.ajax({
        //...
        complete: (typeof successFunctionName === "string" ? window[successFunctionName] : successFunctionName)
    })
}

What you've done is correct.

When calling your callService you would do:

callService(function(resp)
{
    alert('Success: ' + resp);
}):

I think you want to have call back for Ajax success, not complete ?

For success :

 $.ajax({
   ......    
   success: successFunctionName

  });  

For complete :

  $.ajax({
   ......    
  }).done(function(){
     successFunctionName();
  });

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