Recently, I made a text box-based smart prompt. The results are roughly as follows:
When I enter one character each time, the request is sent through ajax and the matching result is returned. When the first character is entered, the ajax request has already started. When the second character is entered, another ajax request is made. In this way, the user needs to input 10 characters for 10 ajax requests, here I need a special requirement to abort or cancel the ajax request when I enter the second character (the premise is that the interval between the two inputs is very short ), when the next ajax request starts, the previous ajax request is aborted or canceled.
var ajaxResult = null;
jQuery("#Keywords").keyup(function () {
jQuery(".SmartTips").hide();
if (jQuery(this).val() != "") {
jQuery("#SmartTips li").children().remove();
var url = "/Product/SearchSmartTips.aspx";
var data = { keyword: jQuery(this).val(), randNum: getDateNum() };
if (ajaxResult != null) {
ajaxResult.abort();
}
ajaxResult = jQuery.get(url, data, function (redata) {
jQuery("#SmartTips").children().remove();
redata = eval("(" + redata + ")");
if (redata.length > 0) {
jQuery(".SmartTips").show();
}
for (var i = 0; i < redata.length; i++) {
jQuery("#SmartTips").append("<li onclick=\"getKeyword('" + redata[i].Keyword + "'," + redata[i].Num + "," + redata[i].Pid + ");\" >" + redata[i].Keyword + "</li>");
}
jQuery("#SmartTips").append("<li style=\"text-align:right;\" onclick=\"closeSmartTips()\">Close</li>");
jQuery("#SmartTips li").hover(function () {
jQuery(this).addClass("hover");
}, function () {
jQuery(this).removeClass("hover");
});
});
}
});
Enter one character in the text box to check whether the XmlHttpRequest object ajaxResult is null. If it is not null, the request is aborted using the abort () method of ajaxResult. abort. The core code is as follows:
var ajaxResult = null;
if (ajaxResult != null) {
ajaxResult.abort();
}
ajaxResult = jQuery.get(url, data, function (redata) {
});
However, in IE7, the abort () method has a bug. if the abort () method is not supported, the message "SCRIPT445: the object does not support this operation" is displayed. If you use jquery 1.42 or any version below
try {
var oldAbort = xhr.abort;
xhr.abort = function() {
if ( xhr) {
oldAbort.call( xhr );
}
onreadystatechange( "abort" );
};
} catch(e) { }
// Replace the above Code in the jquery file with the following code
try {
var oldAbort = xhr.abort;
xhr.abort = function() {
if ( xhr) {
if (oldAbort.call === undefined) {
oldAbort();
} else {
oldAbort.call( xhr );
}
}
onreadystatechange( "abort" );
};
} catch(e) { }
For more detailed solution discussions, please go to the http://forum.jquery.com/topic/object-doesn-t-support-this-property-or-method-from-jquery-1-4-1-in-ie7-only.