例如,假设一个页面根据已删除的用户文本返回搜索结果。
如何解释端点具有高度可变延迟的情况,在这种情况下,第二个调用可以在第一个调用之前返回。
例如。
用户正在键入“图书和电影”,按下500 is键。
用户在中间稍微停顿一下,所以字符串是“book”,这会触发一个搜索调用。
用户继续打字并完成,触发了的第二个调用“图书和电影”.
第二个调用首先返回,基于的“图书和电影”填充列表。
然后,被延迟的第一个调用返回,并根据“book”重新呈现列表。
用户只看到“图书”,感到困惑。
解决这一问题的可靠方法是使用一个按钮手动触发呼叫。不过,我想避免这种情况,所以我增加了抵抗力度,但我想知道是否有更好的办法。
发布于 2016-05-11 06:41:01
我们假设您使用jQuery进行ajax调用。
一种解决方案是使用池系统:基本上是一个包含ajax请求的数组。每次发出新请求时,都会中止池中的所有请求。因此,您确保最后提出的请求将是唯一会结束的请求。
下面是人才库的实现:
jQuery.xhrPool = [];
jQuery.xhrPool.abortAll = function () {
jQuery(this).each(function (idx, jqXHR) {
jqXHR.abort();
});
jQuery.xhrPool.length = 0;
};
下面是如何与GitHub (https://developer.github.com/v3/search/#search-repositories)的“搜索存储库API”一起使用它的示例:
jQuery.xhrPool = [];
jQuery.xhrPool.abortAll = function () {
jQuery(this).each(function (idx, jqXHR) {
jqXHR.abort();
});
jQuery.xhrPool.length = 0;
};
$(document).ready(function(){
$("#SearchField").autocomplete({
source: function( request, response ) {
// First we abort all other request
jQuery.xhrPool.abortAll();
$.ajax({
url: "https://api.github.com/search/repositories",
method: "get",
dataType: "jsonp",
data: {
q: request.term
},
beforeSend: function (jqXHR) {
// Before sending the request we add it to the pool.
jQuery.xhrPool.push(jqXHR);
},
success: function(data) {
var items = new Array();
for(var i=0;i<data.data.items.length;i++)
{
items.push(data.data.items[i].name);
}
response(items);
}
});
},
minLength: 3,
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" >
<input type="text" id="SearchField" />
发布于 2016-05-11 06:24:03
Javascript同步工作,因此如果您正确编写代码,就不可能出现争用条件。
我猜您正在使用ajax (ajax应该是异步的,不要一直使用同步,一旦同步,就不能返回)来获取查询结果。您可能正在使用如下代码:
var req=new XMLHttpRequest();
req.onreadystatechange=function(){
if (req.readyState==4){
if (req.status==200){
// Your callback here which shows autocomplete suggestions maybe?
}
}
}
保留这个req
变量。因此,一旦执行了新请求,就可以简单地丢弃旧请求,例如:
req.onreadystatechange=null;
您还可以像这样中止 ajax请求:
req.abort();
https://stackoverflow.com/questions/37105255
复制相似问题