代码之家  ›  专栏  ›  技术社区  ›  Tim

如何将值传递给jquery ajax成功处理程序

  •  4
  • Tim  · 技术社区  · 16 年前

    在jquery中给出以下Ajax调用:

      {
      .
      .
      .
      ,
      getSomeData: function(args, myUrl, foo) {
            $.ajax( {
            type: "GET",
            url:  myUrl,
            data: args,
            async: true,
            dataType: 'json',
            success: myHandler  
    
             });
     },
    
       myHandler: function (data, textStatus, oHTTP, foo){   ...   }  
    
    };
    

    可以值 foo 以某种方式附加到传递给成功处理程序的参数之后 myHandler ?是否有任何方法可以将值传递到get上的服务器,并使该值在往返过程中返回到客户机,重新出现在成功处理程序的参数列表中?我不能改变返回的内容的结构 data .

    2 回复  |  直到 11 年前
        1
  •  4
  •   Unicron    16 年前

    如果你声明 myHandler 在请求中,可以使用 closure .

    getSomeData: function(args, myUrl, foo) {
            $.ajax( {
            type: "GET",
            url:  myUrl,
            data: args,
            async: true,
            dataType: 'json',
            success: function (data, textStatus, oHTTP){   ...   }  
    
             });
     },
    

    这种方式, foo 您可以在 success 回调。

        2
  •  1
  •   Chris    16 年前

    如果您是一个类中的$.Ajax调用,并且成功回调是通过该类的一个方法传递的,那么它将不起作用。

    编辑:这是答案。注意,我将函数ajaxcall定义为类中的一个方法。我将this.before、this.error和this.success定义为AjaxCall的方法,因为它们可以从超类调用方法。

    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();