jQuery AJAX custom function and custom callback?

前端 未结 3 683
遇见更好的自我
遇见更好的自我 2021-01-05 15:46

Heylow everyone!

I have an ajax() call like so:

$.ajax({
  type: \"post\",
  url: \"whatever.php\",
  data: {
    theData: \"moo moo\"
          


        
3条回答
  •  旧时难觅i
    2021-01-05 16:25

    On this note, you can pass a complete function as a callback to this:

    function customRequest(u,d,callback) {
       $.ajax({
         type: "post",
         url: u,
         data:d,
         success: function(data) {
            console.log(data); // predefined logic if any
    
            if(typeof callback == 'function') {
               callback(data);
            }
         }
      });
    }
    
    
    
    // Then call it as follows:
    
    function initiator() {
    
        customRequest( '/url/to/post', 'param1=val', function() { alert( 'complete' ); })
    
    }
    

    Simply passing it as an anonymous function will work too.. Just for the sake of showing :)

提交回复
热议问题