如何将对象传递给jquery回调?

时间:2015-09-19 08:44:27

标签: javascript ajax object jquery-callback

我有这段代码:

function API() {
    this.status = 'nothing';
}

API.prototype.search = function() {
    this.status = 'searching';

    $.ajax({
        url: 'https://api.com',
        data: {shapeFormat: 'raw'},
        dataType: 'json',
        timeout: 11000,
        success: this.OK_callback,
        error: this.KO_callback
    });
}

API.prototype.OK_callback = function(data) {
    console.log(this.status); // How to pass this value to the function?
}

API.prototype.KO_callback() {
    this.status = 'done';
}

我如何才能访问this.statusOK_callback? 提前谢谢!

1 个答案:

答案 0 :(得分:1)

您需要在适当的环境中调用您的函数。简单的方法是使用Function.prototype.bind方法:

$.ajax({
    url: 'https://api.com',
    data: {shapeFormat: 'raw'},
    dataType: 'json',
    timeout: 11000,
    success: this.OK_callback.bind(this),
    error: this.KO_callback.bind(this)
});

或者您可以使用context设置来设置回调上下文:

$.ajax({
    url: 'https://api.com',
    data: {shapeFormat: 'raw'},
    dataType: 'json',
    timeout: 11000,
    success: this.OK_callback,
    error: this.KO_callback,
    context: this
});