2014-05-09 33 views
0

我試圖創建一個textarea觸發ajax請求onchange。 關鍵是我擔心排隊太多請求到服務器,因爲該請求將保存在數據庫中的這個textarea的內容。 其實我的想法是關於創建一種計時器,在最後一次onchange幾秒後,啓動ajax請求以保存textarea數據。 關鍵是,如果這是一個好主意,我還沒有任何線索,而且,我還沒有弄清楚要寫下來的代碼。 我正在使用JQuery。Ajax後onchange

+0

你試過了什麼? –

+0

使用計時器是一個非常好的主意 - 使用setTimeout和clearTimeout進行調查。 –

回答

3

播放過的Dave's code above

可以節流這些調用的基本思路是檢查是否有計時器

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); 
     } 
    }); 
} 
+0

這一個實際上是我正在尋找。謝謝你 –

+0

完美謝謝你的更新 – Dave

1

嘗試如下,通過延遲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); 
     } 
    }); 
} 
+0

有沒有辦法在創建新的setTimeout之前「取消」以前的setTimeout? –

+1

可能需要超過200毫秒的超時時間......這可能與普通打字一樣快!此外,這不會使用clearTimeout按下另一個鍵時取消預定的帖子。 –

0

好或壞主意:這完全取決於你,你的服務器的接近性,服務器資源和用戶在文本鍵入的號碼:不管怎麼說,定時器的代碼是一樣的東西如下:

<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!)。