简体   繁体   English

Javascript:在函数完成时调用特定函数

[英]Javascript: call a specific function on function complete

I have a slow function that does an AJAX request: 我有一个执行AJAX请求的慢函数:

function X(param1,param2){
var params={
    type: "POST",
    url: "./ajax/useful.php",
    data: "param1="+param1+"&param2="+param2,
    success: function(msg){
      //do something
    }
  };
  var result=$.ajax(params).responseText;
}

Everything works fine when I call X("asdf","qwerty"). 当我调用X(“ asdf”,“ qwerty”)时,一切正常。

Now, what I want to do is to be able to call function X as follows: 现在,我要做的就是能够如下调用函数X:

function X(param1,param2,function(){alert('hi');}){
var params={
    type: "POST",
    url: "./ajax/useful.php",
    data: "param1="+param1+"&param2="+param2,
    success: function(msg){
      /////
      //I want to be able call the function in the 3rd parameter (alert in this case)
      /////
    }
  };
  var result=$.ajax(params).responseText;
}

Now you might say why don't I just call alert('hi') directly inside the success. 现在您可能会说为什么我不直接在成功内部直接调用alert('hi')。 Sure I can do this, but I want to be able to vary what goes on inside the called function (not just a simple alert('hi'), depending on who's calling X. 当然可以,但是我希望能够改变被调用函数内部的情况(不仅仅是简单的alert('hi'),这取决于谁在调用X。

You declare your X function like this: 您可以这样声明X函数:

function X(param1,param2,callback){

...use the callback like this: ...使用这样的回调:

success: function(msg){
    callback();
}

...and call X like this: ...并这样调用X

X('a', 'b', function(){alert('hi');});

This works because your success handler is a closure over the data within your X function, including its arguments. 之所以可行,是因为成功处理程序是对X函数中的数据(包括其参数)的封闭 It has a live reference to that information (even after X returns), and so later when the Ajax call completes, it can still use the callback argument. 它具有对该信息的实时引用(即使在X返回之后),因此稍后在Ajax调用完成时,它仍可以使用callback参数。 More on closures here: Closures are not complicated 有关闭包的更多信息: 闭包并不复杂

function X(param1,param2,f){
var params={
    type: "POST",
    url: "./ajax/useful.php",
    data: "param1="+param1+"&param2="+param2,
    success: function(msg){
      f();
    }
  };
  var result=$.ajax(params).responseText;
}

should work. 应该管用。 You can no call X like this: 您不能像这样呼叫X:

X(param1,param2,function(){dowhatever})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM