Sorun
Geri aramanın içinde, olay işleyicisinin bağlı olduğu öğeyi değil, Ajax çağrısının nesnesini thisifade eder jqXHR. JavaScript'te nasıl thisçalıştığı hakkında daha fazla bilgi edinin .
Çözümler
ES2015 + sizin için mevcutsa, bir ok işlevini kullanmak muhtemelen en basit seçenek olacaktır:
$.ajax({
//...
success: (json) => {
// `this` refers to whatever `this` refers to outside the function
}
});
contextSeçeneği ayarlayabilirsiniz :
Bu nesne, Ajax ile ilgili tüm geri aramaların bağlamı haline getirilecektir. Varsayılan olarak bağlam, çağrıda kullanılan ajax ayarlarını temsil eden bir nesnedir ( $.ajaxSettingsiletilen ayarlarla birleştirilir $.ajax). (...)
$.ajax({
//...
context: this,
success: function(json) {
// `this` refers to the value of `context`
}
});
veya şunu kullanın $.proxy:
$.ajax({
//...
success: $.proxy(function(json) {
// `this` refers to the second argument of `$.proxy`
}, this)
});
veya thisgeri aramanın dışındaki değere bir referans tutun :
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
}
});
İlişkili