javascript - Jquery正在发送多个请求
问题描述
我正在尝试制作一个搜索栏,它会从输入的信件中发送提案请求。jQuery 发送的请求数量与输入的字母数量相同。
如果我写“sa”,jQuery 将发送 2 个请求。如果我写“Sa”,jQuery 将发送 3 个请求(大字母被计为 2 个字母,因为我正在按下 shift 键)。
代码应该像以下说明一样工作:用户写下他想要找到的名称和数据库中的代码搜索,并显示所有可能的搜索词。 编辑: 脚本应该发送 2 请求:第一个获得所有具有“sa”的结果。选择结果后。它应该只向数据库发送一个请求以获取其余信息。我的脚本在做什么:他正在按照他应该做的那样发送第一个请求。第二个请求与字母数量同时发送。即使只有一个请求就足够了
这里还有一个 youtube 视频的链接,我录制了这个视频来解释这个问题
这是我的 jQuery 代码:
$('.sucherInput').on('keyup', function () {
// ** .sucherInput is the class of the input field
var inputValue = $('.sucherInput').val();
var result = $(".sucherres");
var resultList = $(".sucherres ul");
if (inputValue.length) {
console.log(inputValue);
$.post("action/php/artikelSucher.php", {
name: inputValue
}).done(function(data){
// Display the returned data in browser
//console.log(data);
resultList.html(data);
result.show();
}); //.done
} else{
console.log("empty");
resultList.empty();
result.hide();
}
$(document).on("click", ".sucherres ul li p", function(){
//set the search bar value as same as the clicked <p> tag
$('.sucherInput').val($(this).text());
//clear the Proposals list
$(resultList).empty();
$(result).hide();
//renew the value of the search bar
//since im taking the value which have to be searched in the database from the searchbar
var sucherLastIndex = $('.sucherInput').val();
console.log("Getting data from database: " + sucherLastIndex);
//load the data into the HTML file
$("#updateDiv #info").load("action/php/index-preis-liste.php", {
name: sucherLastIndex
});
});
});
这是HTML代码:
<div class="sucher">
<ul style="width: 100%; margin-bottom: 0;">
<li style="width: 33%;">
<input type="text" class="sucherInput" placeholder="Geben Sie einen Suchbegriff ein">
</li>
</ul>
<div class="sucherres">
<ul>
<!-- ## HERE COMES THE Proposals ## -->
</ul>
</div>
<div id="info">
</div>
解决方案
我找到了解决方案**
这是通过改变
$(document).on("click", ".sucherres ul li p", function(){
至
$(document).off('click').on("click", ".sucherres ul li p", function(){
所以只需添加
.off('点击')
**
推荐阅读
- gremlin - 将 Gremlin GraphTraversal 结果与字符串连接起来
- qt - 将 JSON 文件读入 QJsonDocument
- javascript - 如何等待 JS 承诺值
- java - 这是一个多余的 NullPointerException 捕获吗?
- opencv - OpenCV - 从网络摄像头读取时的缓冲区尺寸
- html - HTML 表单验证未出现
- elasticsearch - 如何在 ElasticSearch Aggregation 中包含所有文档并避免 sum_other_doc_count > 0
- rust - 构建 rust Rocket api 时出现“root 中没有'Json'”错误
- reactjs - react-i18next:字符串未翻译
- pagination - 十一(11ty)数据分页 - 来自数据的标题