how to pass a value to jQuery Ajax success-handler

后端 未结 3 819
忘了有多久
忘了有多久 2021-01-13 17:23

Give the following Ajax call in jQuery:

  {
  .
  .
  .
  ,
  getSomeData: function(args, myUrl, foo) {
        $.ajax( {
        type: \"GET\",
        url:         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-13 18:11

    If you're $.ajax call is in a class and the success callback is passed a method of that class, it does not work.

    EDIT: Here is the answer. Note that I am defining the function ajaxCall as a method in a class. I define this.before, this.error, and this.success as methods of ajaxCall because they can call methods from the superClass.

    function main(url){
      this.url = url;
    
      this.ajaxCall = function(){
    
              this.before = function(){
                      //Can call main class methods
                      };
              this.error = function(){
                             //Can call main class methods
                           };
              this.success = function(data){
                               //Can call main class methods
                             };
    
              //This is how you pass class arguments into the success callback
              var that = this;
    
              $.ajax({ 
                url: this.url,
                type: 'GET',
                dataType: 'json',
                beforeSend: this.before(),
                    error: this.error(),
                success: function(data){that.succes(data);}
              });
    
      //Run internally by calling this.ajaxCall() after it is defined
      //this.ajaxCall();
    }
    
    //Or externally
    var main = new main(SOME_URL);
    main.ajaxCall();
    

提交回复
热议问题