ปัญหา
ภายในการเรียกกลับthis
หมายถึงjqXHR
ออบเจ็กต์ของการเรียก Ajax ไม่ใช่องค์ประกอบที่ตัวจัดการเหตุการณ์ถูกผูกไว้ เรียนรู้เพิ่มเติมเกี่ยวกับวิธีการ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
}
});
ที่เกี่ยวข้อง