javascript的回调函数里如何传递参数

2024-12-07 11:05:08
推荐回答(3个)
回答1:

function doAjax(u,param,callback){
$.ajax({
type:'POST',
url:u,
data:param,
success:callback
});
}

function showAlert(data,test1,test2){

alert(data+" "+test1+" "+test2);
}

window.onload = doAjax("server.php","id=12&type=1",function(data){showAlert(data,3,5)});
执行doAjax的时候,回调函数的调用改一下就可以了。
测试过没问题。

回答2:

简单,很多方法都定义了回调函数,回调函数也是函数,就是说不管怎么传,只需要是个函数类型即可。写法如下。
方式1,
doAjax(参数1,参数2,function(request,opts){
callback(request,opts,agrs);
});
function callback(request,opts,args){

};
方式2,
var args=N;
doAjax(参数1,参数2,function(request,opts){
var X=N;
回调函数代码块..
和以上几乎一样,看个人编码方式选择。
});

回答3:

  回调函数就是一个通过函数指针调用的函数。如果把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。

  回调函数写法如下:

  【方法1】

doAjax(参数1,参数2,function(request,opts){
         callback(request,opts,agrs);
 });
function callback(request,opts,args){
              
};


  【方法2】

var args=N;
doAjax(参数1,参数2,function(request,opts)
{
       var X=N;
       回调函数代码块
};