Jquery $(此)AJAX内部成功不起作用
我试图更改一些使用onclick的旧代码,以便使用$(this)。问题是$(this)在success中不起作用。在不将其设置为var的情况下,是否仍然可以执行此操作Jquery $(此)AJAX内部成功不起作用,jquery,Jquery,我试图更改一些使用onclick的旧代码,以便使用$(this)。问题是$(this)在success中不起作用。在不将其设置为var的情况下,是否仍然可以执行此操作 $('.addToCart').click(function() { $.ajax({ url: 'cart/update', type: 'post', data: 'product_id=' + $(this).attr("data-id"), data
$('.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
对象,而不是事件处理程序绑定到的元素
解决 如果您可以使用ES2015+,那么使用箭头功能可能是最简单的选择:
$.ajax({
//...
success: (json) => {
// `this` refers to whatever `this` refers to outside the function
}
});
您可以设置:
此对象将成为所有Ajax相关回调的上下文。默认情况下,上下文是表示调用中使用的ajax设置的对象($.ajaxSettings
与传递给$.ajax
的设置合并)。(……)
或使用:
或者在回调外部保留对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
}
});
相关的
$.ajax({
//...
success: $.proxy(function(json) {
// `this` refers to the second argument of `$.proxy`
}, 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
}
});
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) {
}
});