给ajax()方法中的success函数传入参数

在做项目的过程中,在ajax()方法中向后台请求成功后,需要在success()方法中调用自定义的参数,刚开始的写法如下:

<script>
   var name = 'hello';
   function getTypeList(){
    $.ajax({
      url :url,    //填写实际的url
      type : 'post',
      contentType : "text/html;charset=utf-8",
      dataType : 'json',
      success : function(response,name) {      
              alert(name);
         mycallback(response,name);//回调函数
      }
      });
   }
</script> 


问题:alert()函数的输出为:“success”,但是明明定义了name为全局变量,值为“hello”

分析:success()函数是ajax()向后台请求成功后自动调用的,在success(response)函数里面的变量只有一个,且里面不能调用自定义的变量,response是后台返回来的值。

需求:如果确实需要在success()函数里面调用自定义的变量,可以将ajax()函数封装起来,由外部函数传入自定义的参数

例如:

<script>
   var name = 'hello';
   function getTypeList(name){ 
          $.ajax(
              { url : '<c:url value="admin/type_loadTypeList.action"/>',  
               type : 'get',   
                contentType : "text/html;charset=utf-8",   
               dataType : 'json',   
               success : function(data) {      
                              alert(name);//查看name的值      
                              mycallback(data,name);//回调函数    
                } 
           }); 
      }
</script>

success()通过调用getTypeList(name)传入的变量

猜你喜欢

转载自blog.csdn.net/u012501054/article/details/81746801