【问题标题】:How pass object to jquery callback?如何将对象传递给 jquery 回调?
【发布时间】:2015-12-16 10:29:58
【问题描述】:

我有这个代码:

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.status value insie OK_callback? 提前致谢!

【问题讨论】:

    标签: javascript ajax object jquery-callback


    【解决方案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
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-21
      • 2011-12-28
      • 2016-09-03
      • 1970-01-01
      • 2013-08-20
      • 1970-01-01
      • 2011-02-02
      • 2014-10-02
      相关资源
      最近更新 更多