我試圖創建一個textarea觸發ajax請求onchange。 關鍵是我擔心排隊太多請求到服務器,因爲該請求將保存在數據庫中的這個textarea的內容。 其實我的想法是關於創建一種計時器,在最後一次onchange幾秒後,啓動ajax請求以保存textarea數據。 關鍵是,如果這是一個好主意,我還沒有任何線索,而且,我還沒有弄清楚要寫下來的代碼。 我正在使用JQuery。Ajax後onchange
回答
可以節流這些調用的基本思路是檢查是否有計時器
var requestTimer;
$('#textarea').on('change', function() {
if (requestTimer) window.clearTimeout(requestTimer); //see if there is a timeout that is active, if there is remove it.
requestTimer = setTimeout(submitFormAjax, 1000); //delay before making the call
});
您還可以檢查是否存在活動的Ajax請求。
var requestTimer;
var xhr;
$('#textarea').on('change', function() {
if (requestTimer) window.clearTimeout(requestTimer); //see if there is a timeout that is active, if there is remove it.
if (xhr) xhr.abort(); //kill active Ajax request
requestTimer = setTimeout(submitFormAjax, 1000); //delay before making the call
});
function submitFormAjax() {
xhr = $.ajax({
type:"POST",
url:"ajax.php",
data:$('#textarea').val(),
success:function(data) {
$("#result").html(data);
}
});
}
這一個實際上是我正在尋找。謝謝你 –
完美謝謝你的更新 – Dave
嘗試如下,通過延遲Ajax調用幾秒鐘減少調用的次數,看看用戶是否要繼續鍵入
var timeoutId;
$('#textarea').on('change', function() {
if(timeoutId){
// prevent last timeout from sending the ajax call
clearTimeout(timeoutId);
timeoutId = 0;
}
timeoutId =setTimeout(submitFormAjax, 200);
return false;
});
function submitFormAjax() {
$.ajax({
type:"POST",
url:"ajax.php",
data:$('#textarea').val(),
success:function(data) {
$("#result").html(data);
}
});
}
有沒有辦法在創建新的setTimeout之前「取消」以前的setTimeout? –
可能需要超過200毫秒的超時時間......這可能與普通打字一樣快!此外,這不會使用clearTimeout按下另一個鍵時取消預定的帖子。 –
好或壞主意:這完全取決於你,你的服務器的接近性,服務器資源和用戶在文本鍵入的號碼:不管怎麼說,定時器的代碼是一樣的東西如下:
<textarea id="textarea"></textarea>
var textTimeout = null;
$("#textarea").on("keyup", function() {
var $that = $(this);
cancelTimeout(textTimeout);
textTimeout = setTimeout(function() {
$.post("www.example.com", { data: $that.val() }, function() {
alert("Posted all text!");
});
}, 2000);
});
但是,如果您在jQuery中使用「更改」事件,那麼只有在對textarea失去焦點時纔會發生這種情況,所以您不必擔心請求排隊(yey!)。
- 1. Onchange()for AJAX
- 2. 提交AJAX Post onchange
- 3. Ajax for Rails 3:onchange
- 4. 添加選擇onchange與AJAX
- 5. Rails 3 select and onchange without Ajax
- 6. AJAX onchange圖片上傳
- 7. AJAX Calendar Extender onchange事件
- 8. 表單提交後AJAX onchange行爲更改
- 9. ASP:在onchange事件後NET ajax函數不起作用
- 10. onchange ajax得不到工作表單方法後
- 11. jquery onchange受事後影響?
- 12. JSF onchange然後保存
- 13. 保持jQuery onChange替換後
- 14. PHP和Ajax使用onchange事件
- 15. Ajax日期選擇onchange值的問題
- 16. onchange使用ajax,codeigniter,下拉菜單
- 17. Rails,select_tag,:onchange =>不是ajax請求
- 18. ajax互聯網瀏覽器onchange
- 19. 通過AJAX發送圖片onchange
- 20. 保存表單變量onchange與ajax
- 21. 在ajax返回上綁定onChange
- 22. AJAX調用MVC中的OnChange事件
- 23. AJAX文件上傳onchange,而不是onsubmit
- 24. Rails 3&Ajax date_select onchange =>提交
- 25. 選擇框onchange事件的AJAX代碼
- 26. Rails的select_tag onchange動作沒有Ajax?
- 27. AJAX請求onchange不起作用
- 28. 調用Ajax響應文本中粘貼responseText後出現的Javascript onchange函數
- 29. Javascript onChange輸入百分比後輸入
- 30. Onchange單選按鈕克隆後
你試過了什麼? –
使用計時器是一個非常好的主意 - 使用setTimeout和clearTimeout進行調查。 –