如何在ajax中调用javascript对象的方法

How to call a method of a javascript object inside ajax

本文关键字:javascript 对象 方法 调用 ajax      更新时间:2023-09-26

给定此代码,

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_id是形式id,并使用查找输出

console.log(res);

在控制台中,它显示undefined。在使用谷歌和stackoverflow本身搜索解释后,我得到了这样的想法,

this.ret(result.message);

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

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

有人能向我解释吗?

有几种方法可以处理它。

其中一个是兼容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或将success作为对象方法。正如它在其他答复中提到的那样。同样,您希望保持this为对象的上下文。

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

您有两个选项。

1."bind()"方法(推荐)

方法CCD_ 10用于改变函数的上下文。来自文档:

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
  }
});

CCD_ 14也可以写成CCD_;

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
  }
});
success: function(result) {
    this.ret(result.message);
}

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

我有一个小代码片段,模拟如下:

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

在提交中定义

self = this

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