如何在"jQuery.ajax({success:function(data)"中设置回调函数参数,如'data'?

Mat*_*hew 2 javascript callback

我想知道如何将回调函数的第一个参数设置为我想要的,就像jquery在成功回调或完整回调中所做的那样

我想做这个:

$.ajax({
  success: function(data) {
    alert(data)
  }
});
Run Code Online (Sandbox Code Playgroud)

根据我的理解,这就像我能达到我想要的那样接近

function test(text) {
  this.text = text
  this.success = function(this.text) { }
}

var a = new test('King Kong')
a.success = function(k){
  alert(k)
}
Run Code Online (Sandbox Code Playgroud)

我希望警报说"金刚"

T.J*_*der 7

这是一个在构造函数中接受回调然后在响应某个触发器时调用它的示例.在下面,触发器是有人调用该trigger函数,但它可以是你想要的任何东西:

function Test(text, callback) {

  this.text = text;
  this.success = callback;
}

Test.prototype.trigger = function() {
    // Call the success callback, passing in the text
    this.success(this.text);
};

var a = new Test('King Kong', function(k) {
    alert(k);
});

a.trigger();
Run Code Online (Sandbox Code Playgroud)

(我Test最初是在那里制作的.这是构造函数的惯例,你当然可以忽略它.)

理解的关键,基本要素是函数就像对象一样.您可以将引用传递给它们等.要调用函数,您只需访问存储函数引用的任何变量并添加括号(可选择在括号中使用函数的参数).

因此,以下所有内容都会调用该foo函数并触发警报:

function foo(msg) {
    alert(msg);
}

var f = foo;   // No parens, just getting the function reference, not calling it
f("Hi there"); // Now we're calling it
var a = {};
a.nifty = f;
a.nifty("Hi again");

function bar(func) {
    func("Hello for the third time");
}
bar(foo);     // Passing a reference to `foo` into the `bar` function, which will call it
Run Code Online (Sandbox Code Playgroud)

高级:现在,jQuery做的一件事是它调用回调,并将this值设置为特定的值(通常是与调用相关的DOM元素).只要通过对象属性调用函数,就会发生这种情况:

var a = {name: "Fred"};
a.func = function() {
    alert(this.name);
};
a.func(); // alerts "Fred"
Run Code Online (Sandbox Code Playgroud)

......但这不是你能做到的唯一方法; 还有函数对象本身的函数callapply函数:

var a = {name: "Fred"};
function func() {
    alert(this.name);
}
func.call(a); // alerts "Fred"
Run Code Online (Sandbox Code Playgroud)

在那里,函数没有分配给任何a属性,但是我们调用了函数using call,它接受this作为第一个参数的值.调用还会传递您正在调用的函数的任何其他参数:

function func(msg1, msg2) {
   alert(this.name + " says " + msg1 + " and " + msg2);
}
var a = {name: "Fred"};
func.call(a, "one", "two"); // alerts "Fred says one and two"
Run Code Online (Sandbox Code Playgroud)

apply 完全相同的事情,但它接受参数作为数组而不是作为离散参数传递给底层函数:

function func(msg1, msg2) {
   alert(this.name + " says " + msg1 + " and " + msg2);
}
var a = {name: "Fred"};
func.apply(a, ["one", "two"]); // alerts "Fred says one and two"
//            ^------------^----- note these args are now an array
Run Code Online (Sandbox Code Playgroud)

更多阅读:神话方法