Ajax ไม่ได้ถูกยกเลิกเมื่อมีการคลิกปุ่ม

ฉันจะยกเลิกการร้องขอ ajax เมื่อคลิกปุ่มได้อย่างไร ฉันลองคำตอบที่พบที่นี่แต่ไม่ได้ผลกับฉัน

<button type="button" id="toStop">Stop</button>

เมื่อคลิกปุ่มหยุดแล้ว อาแจ็กซ์ก็ไม่ถูกยกเลิก

function() {
    var myajaxreq = $.ajax({
        url: myurlhere,
        type: 'GET',
        async: true,
        success: function(result) {
                            
        }
        beforeSend: function () {
            if(document.getElementById('toStop').clicked == true) {
                myajaxreq.abort();
            }
        }
    });
}

person Denver Leetrich    schedule 16.06.2020    source แหล่งที่มา
comment
ไม่มีคุณสมบัติที่ถูกคลิก และหากใช้งานได้ คุณจะต้องตรวจสอบก่อนที่จะส่งเท่านั้น   -  person epascarello    schedule 07.07.2020


คำตอบ (1)


คุณต้องมี Listener การคลิกแยกต่างหากซึ่งจะยกเลิกคำขอ Ajax การใช้ beforeSend จะไม่ได้ผลเสมอไป

$('#toStop').click(function(e) {
    e.preventDefault();
    // abort here
    // make sure myajaxreq is accessible in this function
    if (myajaxreq) myajaxreq.abort();
}); 
person artfulbeest    schedule 16.06.2020