【发布时间】:2013-11-12 17:12:50
【问题描述】:
我正在尝试关注the advice within this question 以适应以下情况:
在 keyup 时,向服务器发送一个 AJAX 请求,并在输入字段中包含术语。但如果他们继续输入,则中止任何现有的 AJAX 请求,因此只发送一个请求。
这是我的代码:
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();
};
});
});
我有两个问题:
- 这种方法是否适用于我想要实现的目标
- 上面的代码出现“Uncaught TypeError: Cannot call method 'abort' of undefined”错误。我哪里错了。
我对 AJAX 还很陌生,所以请原谅我的幼稚。
【问题讨论】:
-
返回
process_asr_request()中的XHR -
没有必要中止它。您可以简单地忽略它,因为 AJAX 无论如何都是异步的。而不是
requests,只需使用一个request并在keyup 上覆盖之前的请求。 -
为了更好的用户界面,考虑使用 333ms 超时和 oninput 而不是 onkeyup
-
据我了解,
oninput还没有在 jQuery 中:stackoverflow.com/questions/11189136/… -
至于
setTimeout建议,您会建议在代码中的哪个位置包含它?在if (inputCount > 2) {语句中?
标签: javascript ajax performance jquery