次のシナリオに適合するように、この質問内のアドバイスに従おうとしています。
キーアップ時に、入力フィールドに用語を指定して AJAX リクエストをサーバーに送信します。ただし、入力を続ける場合は、既存の AJAX 要求を中止して、1 つの要求のみが送信されるようにします。
これが私のコードです。
jQuery(document).ready(function($) {
var $input = $('#s'),
inputVal = '',
inputCount = '';
function process_asr_request() {
$.ajax({
url: MyAjax.ajaxurl,
data: {
'action':'pondera_asr_request',
'inputVal' : inputVal
},
success:function(data) {
$('#search-results').append( data )
},
error: function(errorThrown){
console.log( errorThrown);
}
});
}
$input.on("keyup", function() {
// record the value of the input
inputVal = $input.val(),
// check the lenght on the value
inputCount = inputVal.length,
// define array for ajax requests
requests = [];
// Only process once there are 3 characters
if (inputCount > 2) {
// push ajax requests into the array
requests.push(
process_asr_request(i)
);
// loop through the array of requests
for(
var i = 0;
i < requests.length;
i++
)
// kill any queued requests
requests[i].abort();
};
});
});
2 つの質問があります。
- このアプローチは、私が達成しようとしているものに対して有効ですか
- 上記のコードで「Uncaught TypeError: Cannot call method 'abort' of undefined」エラーが発生します。どこが間違っているのですか。
私はAJAXにかなり慣れていないので、私の素朴さを許してください。