0

Почему я не могу присвоить значение переменной showModal , внутри ajax функции ? this.showModal = true; - показывает popup окно. Как сделать правильно ? Пример кода:

$.ajax({
  url: 'url',
  type: "POST",
  data: {
    action: "send",
    phone : this.tel
  },
  dataType:'JSON',
  success: function (response) {

    if (response.id) {
        this.showModal = true;
    } else {
        console.log("Error");
        console.log(response);
    }
  }
});

1 ответ 1

1

конструкция function изменяет контекст(this) : тоисть внутри функции this ссылается на другой объект. решение №1: простое решение это стрелочная функция

$.ajax({
  url: 'url',
  type: "POST",
  data: {
    action: "send",
    phone : this.tel
  },
  dataType:'JSON',
  success: (response)=>{

    if (response.id) {
        this.showModal = true;
    } else {
        console.log("Error");
        console.log(response);
    }
  }
});

решение №2: создать ссылку на нужный объект this в области выше видимости, и потом применять эту ссылку

var _this = this;
$.ajax({
  url: 'url',
  type: "POST",
  data: {
    action: "send",
    phone : this.tel
  },
  dataType:'JSON',
  success: function (response) {

    if (response.id) {
        _this.showModal = true;
    } else {
        console.log("Error");
        console.log(response);
    }
  }
});

решение №3: тру программисты может так и делают, но я так не люблю делать, очень стрёмно

$.ajax({
  url: 'url',
  type: "POST",
  data: {
    action: "send",
    phone : this.tel
  },
  dataType:'JSON',
  success: (function (response) {

    if (response.id) {
        this.showModal = true;
    } else {
        console.log("Error");
        console.log(response);
    }
  }).bind(this)
});
1
  • Спасибо большое за ответ и объяснение
    – Goryyn
    22 авг 2019 в 6:01

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.