【问题标题】:Succes funcion not working after transfer parameter from class [duplicate]从类传输参数后成功功能不起作用[重复]
【发布时间】:2019-12-16 05:07:04
【问题描述】:

我创建类。一切正常,但成功功能不重定向。为什么?

class Ajax {
  constructor(url, method, dataType, reDirect, alert) {
    this.url = url,
      this.method = method,
      this.dataType = dataType,
      this.reDirect = reDirect,
      this.alert = alert
  }

  getAJAX() {
    $.ajax({
      url: this.url,
      method: this.method,
      dataType: this.dataType,
      success: function(result) {
        window.location = this.reDirect
      },
      error: function(result) {
        alert(this.alert)
      }
    })
  }
}

这是我从类中调用方法的方式:

const clearConf = new Ajax('/ConfigurationHistories/ClearList', 'GET', 'text', '/ConfigurationHistories/Index', 'Not clear list.')
clearConf.getAJAX()

【问题讨论】:

  • success 处理函数中的 this 不包含对您的 Ajax 类的引用。您需要将其缓存在处理程序之外或使用箭头函数(假设您根本不需要支持 IE)。有关详细信息,请参阅副本

标签: javascript jquery object


【解决方案1】:

因为thissuccess 函数中被重新分配。使用箭头函数:

success: () => {
  window.location = this.reDirect;
}

或者使用bind:

success: function() {
  window.location = this.reDirect;
}.bind(this);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多