【问题标题】:How to call a method of a javascript object inside ajax如何在ajax中调用javascript对象的方法
【发布时间】:2016-09-10 09:03:55
【问题描述】:

鉴于此代码,

var submit = {
  send:function (form_id) {
    var url = $(form_id).attr("action");
    $.ajax({
      type: "POST",
      url: url,
      data: $(form_id).serialize(),
      dataType: 'json',
      success: function(result) {
        this.ret(result.message);
      },
      error: function(result) {
        // Some error message
      }
    });
  },

  ret:function (result) {
    this.result_data = result;
  },

  result_data:""
};

将表单中的数据发送到控制器,如果控制器返回一个 json

$result['message'] = validation_errors();
echo json_encode($result); 

我尝试在这段代码中调用这个 javascript 对象,

var res = submit.send(form_id);

其中form_idid的形式,使用

查找输出
console.log(res);

在控制台中,它显示undefined。在使用 google 和 stackoverflow 本身搜索解释后,我想到了,

this.ret(result.message);

在另一个对象的 ajax 内部被调用,表明它不是它的方法的一部分。

我的问题是,如何在ajax内部调用ret()方法?

谁能给我解释一下?

【问题讨论】:

  • 是的,但是使用控制台查看时返回未定义
  • @brett dewoody:这可能吗,它需要一个函数,还是我错了?

标签: javascript jquery ajax object


【解决方案1】:

有几种方法可以处理它。

一个是 ES5 兼容的(这实际上是很常见的模式):

var submit = {
send: function (form_id) {
  var url = $(form_id).attr("action");
  var self = this; // << this is binded to self varialble
  $.ajax({
    type: "POST",
    url: url,
    data: $(form_id).serialize(),
    dataType: 'json',
    success: function(result) {
      self.ret(result.message); // << replaced this to self so it has all the methods from the submit object.
    },
    error: function(result) {
      // Some error message
    }
  });
},

ret:function (result) {
  this.result_data = result;
},

result_data:""
};

另一个是使用 ES2015 中的箭头函数加上 $.ajax 返回的延迟对象:

var submit = {
send: function (form_id) {
  var url = $(form_id).attr("action");
  $.ajax({
    type: "POST",
    url: url,
    data: $(form_id).serialize(),
    dataType: 'json'
  })
  .then((result) => {
    this.ret(result.message); // << arrow function is called in context of the parent function, so no needs to change anything.
  })
  .fail(function(result) {
    // Some error message
  });
},

ret:function (result) {
  this.result_data = result;
},

result_data:""
};

说明:回调函数中this 的上下文将绑定到全局范围而不是对象的范围。所以你需要以某种方式改变它。

你实际上可以匹配和混合这两种方法。

您也可以使用bind 或将成功作为对象方法。正如其他答案中提到的那样。同样,您希望将 this 保留为对象的上下文。

There 是一篇关于 javascript 中 this 的好文章。

【讨论】:

  • 不完全是我的问题的具体解决方案,因为每当我尝试在控制台上查看结果时,我不知道为什么仍然继续返回 undefined 但使用你的想法我想出了另一个解决方案.谢谢。其余的答案也有效。太好了!
【解决方案2】:

你有两个选择。

1。 “bind()”方法(推荐)

bind 方法用于更改函数的上下文。来自docs

bind() 方法创建一个新函数,在调用该函数时,该函数具有 此关键字设置为提供的值,具有给定的序列 调用新函数时提供的任何参数之前的参数。

这里bind 将使用this 的引用更改成功函数的上下文,即submit

$.ajax({
  type: "POST",
  url: url,
  data: $(form_id).serialize(),
  dataType: 'json',
  success: function(result) {
    this.ret(result.message);
  }.bind(this),                  // <== bind method
  error: function(result) {
    // Some error message
  }
});

.bind(this)也可以写成.bind(submit)

2。使用范围变量

既然您已经可以访问submit 变量,为什么不直接使用submit 而不是this 调用

$.ajax({
  type: "POST",
  url: url,
  data: $(form_id).serialize(),
  dataType: 'json',
  success: function(result) {
    submit.ret(result.message);
  }.bind(this),
  error: function(result) {
    // Some error message
  }
});

【讨论】:

    【解决方案3】:
    success: function(result) {
        this.ret(result.message);
    }
    

    在上面的块中,this 指的是你正在操作的函数。 要使用ret 方法,您应该使用它submit.ret

    【讨论】:

      【解决方案4】:

      我有一个小代码片段,可以模拟这个:

      var submit = {
        send:function (form_id) {
          var self = this;
          setTimeout(function()
          { 
            console.log('send', this);
            self.ret('message'); //will do
            //submit.ret('message'); //will do
              //this.ret('message'); this.ret is not a function
            //ret('message'); ret is not defined
          }, 0);    
        },
      
        ret:function (result) {
          console.log('ret', result, this)
          this.result_data = result;
        },
      
        result_data:""
      };
      

      在那里您可以看到处理此问题的可能选择。

      或者使用这个小提琴:https://jsfiddle.net/syqjwk2q/#&togetherjs=mpwEnNDeIJ

      【讨论】:

        【解决方案5】:

        在提交定义中

        self = this
        

        然后将ret()self 一起使用:self.ret()

        【讨论】:

          猜你喜欢
          • 2016-02-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-10
          • 1970-01-01
          • 2018-03-20
          • 2011-04-12
          相关资源
          最近更新 更多