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

时间:2015-11-18 09:42:04

标签: javascript ajax marionette

我需要从ajax 成功方法调用 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 = "/";
}

2 个答案:

答案 0 :(得分:1)

通过创建一个引用(可以从AJAX success回调的范围中看到)到保存onSuccessLogin的对象。

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

另请参阅ES6 Arrow functions上的MDN参考 - 将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 = "/";
}

答案 1 :(得分:0)

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

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

}  

}); 

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