$AJAX内部的成功不起作用



我正在尝试更改一些使用onclick的旧代码,以便可以使用$(this)。问题是,在成功内部,$(this)不起作用。有没有办法在不将其设置为var.的情况下做到这一点

$('.addToCart').click(function() {
    $.ajax({
        url: 'cart/update',
        type: 'post',
        data: 'product_id=' + $(this).attr("data-id"),
        dataType: 'json',
        success: function(json) {
            if (json['success']) {
            $(this).addClass("test");
            }   
        }
    });
});

问题

在回调中,this指的是Ajax调用的jqXHR对象,而不是事件处理程序绑定到的元素。了解有关this在JavaScript中如何工作的更多信息。


解决方案

如果您可以使用ES2015+,那么使用箭头功能可能是最简单的选择:

$.ajax({
    //...
    success: (json) => {
         // `this` refers to whatever `this` refers to outside the function
    }
});

您可以设置context选项:

这个对象将成为所有Ajax相关回调的上下文。默认情况下,上下文是一个表示调用中使用的ajax设置的对象($.ajaxSettings与传递给$.ajax的设置合并)(…)

$.ajax({
    //...
    context: this,
    success: function(json) {
         // `this` refers to the value of `context`
    }
});

或使用$.proxy

$.ajax({
    //...
    success: $.proxy(function(json) {
         // `this` refers to the second argument of `$.proxy`
    }, this)
});

或者在回调之外保留对this值的引用:

var element = this;
$.ajax({
    //...
    success: function(json) {
         // `this` refers to the jQXHR object
         // use `element` to refer to the DOM element
         // or `$(element)` to refer to the jQuery object
    }
});

相关

  • 如何在回调中访问正确的"this"
jQuery(".custom-filter-options .sbHolder ul li a").each(function () {
    var myStr = jQuery(this).text();
    var myArr = myStr.split(" (");
     url = 'your url'; // New Code
            data = myArr[0];
                try {
                    jQuery.ajax({
                        url : url,
                        context: this,
                        type : 'post',
                        data : data,
                        success : function(data) {
            if(data){
                  jQuery(this).html(data);
            }else{
                  jQuery(this).html(myArr[0]);
            }
                        }
                    });
                } catch (e) {
                } 

});

最新更新