如何在ajax函数中回调`this`

乔纳斯

所以我想this从 ajax 成功函数中的外部函数中使用。我试图应用这些解决方案,但不知何故我无法让它发挥作用。

// Submit vote on submit
$('.vote-choice-div').on('click', function(event){
    event.preventDefault();

    // bind the clicked object
    this.submit_vote.bind(this);    // so I have to bind the element to use it in the ajax function?

    // fire ajax
    submit_vote(this.id, this);

});
// AJAX for posting
function submit_vote(vote) {

    $.ajax({
            url : "submit-vote/",
            headers: {'X-CSRFToken': csrftoken}, 
            type : "POST",
            data : { vote : vote }, 

            success : function(data) {
                 if(data.status === 1){
                    
                     console.log(this)   // can't access the initial clicked element
                 }

未捕获的类型错误:无法读取未定义的属性(读取“绑定”)

昆汀

你有两个问题(和一个毫无意义的争论)。

  1. submit_vote是全局的,而不是元素的属性。要访问它,您不使用this.
  2. bind 返回一个新函数。它不会改变现有的
  3. submit_vote 只接受一个参数

所以:

const localSubmitVote = submit_vote.bind(this)
localSubmitVote(this.id);

但是……bind仅当您要存储一个函数以便您可以传递它或多次使用它时才有用。

你没有这样做,你只调用一次,所以使用 call

submit_vote.call(this, this.id);

但是……submit_vote不是方法。将它设计为首先使用是不明智的this所以这里更好的方法是重新设计它,只使用你之前传递的第二个参数。

function submit_vote(vote, element) {
  $.ajax({
    // ...
    success: function(data) {
      if (data.status === 1) {
        console.log(element);
      }
    }
  });
}

submit_vote(this.id, this)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章