2016-06-23 65 views
0

我有一個Ruby on Rails 4.2應用程序。Rails UJS:當觸發一個新的Ajax請求時放棄以前觸發但仍然活動的Ajax請求

我有3個按鈕,觸發AJAX請求使用Rails UJS

<section id="buttons"> 
    <%= link_to image_tag(image), 
     button1_modal_path, 
     remote: true, 
     id:"icon1", 
     data: { disable_with: '' } %> 
    <%= link_to image_tag(image), 
     button2_modal_path, 
     remote: true, 
     id:"icon2", 
     data: { disable_with: '' } %> 
    <%= link_to image_tag(image), 
     button3_modal_path, 
     remote: true, 
     id:"icon3", 
     data: { disable_with: '' } %> 
</section> 

我希望實現以下模式:

  • 用戶點擊按鈕1推出AJX XHR請求(讓(我們稱它爲ajaxRequest1)

  • ajax仍在處理中(以及它所處的狀態:已發送,已經由服務器處理過,在它回來之前......),但沒有t到達(200)和用戶點擊按鈕2觸發另一個xhr ajax請求(ajaxRequest2)

  • 我想在這種情況下,所有其他活動的ajax請求(也就是說在這種情況下ajaxRequest1)被取消。如果有比只多了一個請求的更多,這將取消所有這些除了最後一個Ajax請求(即ajaxRequest2)

我想這使用Rails UJS ajax events,但它不工作(實際上取消所有Ajax請求被觸發:(:

on('ajax:beforeSend',function(event, xhr, settings){ 
    xhr.onreadystatechange = null; 
    xhr.abort(); 
} 

注:我想,我不只是取消瀏覽器正在等待Ajax請求返回的事實,並顯示其內容,但也是如果在最好的情況下請求已經啓動,但尚未命中服務器,它在被服務器命中之前被取消,以免超出用無用的阿賈克斯請求加入服務器

回答

1

要取消請求1,你應該調用根據請求1中止XMLHttpRequest對象上,例如

ajaxRequest1.abort(); 

你的代碼的含義是在發送之前中止的請求。

on('ajax:beforeSend',function(event, xhr, settings){ 
    xhr.onreadystatechange = null; 
    xhr.abort(); 
}