如何从嵌套的ajax(成功)方法中调用外部方法?

How to call external method from nested ajax (success) method?

我需要从 ajax success 方法调用 onSuccessLogin 方法,或者将响应作为参数放入 onSuccessLogin。 谢谢你的回答。

submit: function (form) {

      $.ajax({
        type: "post",
        url: "/login",
        data: {
          login: $(form).find('#login').val(),
          password: $(form).find('#password').val(),
          deviceType: environmentInfo.browser,
          sdkVersion: environmentInfo.browserVersion,
          osVersion: environmentInfo.OS
        },

        success: function(res) {
          localStorage.setItem("languagesList", res);
          //how to call onSuccessLogin method from here?
        },

     //Another implementation
        // success: this.onSuccessLogin(res), - dosen't work, if I want put response from ajax into this method call

        error: this.onErrorLogin
      });
    },

onSuccessLogin: function () {
  //localStorage.setItem("languagesList", res); get response from second implementation
  window.location = "/";
}

通过创建对持有onSuccessLogin.

对象的引用(从AJAX success回调的范围可以看出)

submit 方法(作为 onSuccessLogin 的兄弟)中,该对象是 this.

另请参阅 MDN 参考 ES6 Arrow functions - 绑定 this 到封闭范围的抽象。

submit: function (form) {

      var self = this;
  
      $.ajax({
        type: "post",
        url: "/login",
        data: {
          login: $(form).find('#login').val(),
          password: $(form).find('#password').val(),
          deviceType: environmentInfo.browser,
          sdkVersion: environmentInfo.browserVersion,
          osVersion: environmentInfo.OS
        },

        success: function(res) {
          localStorage.setItem("languagesList", res);
          self.onSuccessLogin();
        },

     //Another implementation
        // success: this.onSuccessLogin(res), - dosen't work, if I want put response from ajax into this method call

        error: this.onErrorLogin
      });
    },

onSuccessLogin: function () {
  //localStorage.setItem("languagesList", res); get response from second implementation
  window.location = "/";
}

我不知道这个逻辑是否正确,如果您将函数放在 ajax 循环之外它会起作用。

$.ajax({
    url: 'test',
    success: function(data) {
    alert("received contents="+data);
    onSuccessLogin();

}  

}); 

 function onSuccessLogin() {
        alert("Successfully logged!!!");
        }