Ajax post-request-.empty()函数由于某种原因无法工作



我有一个潜在的错误,我的搜索栏通过ajax进行发布请求。但在第一次请求时,它会清除dom并附加结果,但在随后的请求中,它不会清除dom。请帮忙?

$("#search_button").click(function() {
const search = $("#search_input").val();
console.log("*******_____________ search __________", search);
//sends a post request to route /search in endpoint.js
$.post("/en/search",
{
search
},
function(data, status) {
//emptying the body and appending the new result
$(".featured_listings_title").empty();
$(".featured_listings_title").append(`<h4>Search results 🎉</h4>`);
for (item of data) {
$(".featured").append(searchTemplate(item));
}
$(".main_feed").empty();
});
});

不确定您要做什么。但在追加之前应该清空。它们也需要在循环中,所以每次循环运行时,它都会清除dom,否则只会清除dom一次。试试这个:-

$("#search_button").click(function() {
const search = $("#search_input").val();
console.log("*******_____________ search __________", search);
//sends a post request to route /search in endpoint.js
$.post("/en/search",
{
search
},
function(data, status) {

for (item of data) {
//emptying the body and appending the new result
$(".featured_listings_title").empty();
$(".main_feed").empty();
$(".featured_listings_title").append(`<h4>Search results 🎉</h4>`);
$(".featured").append(searchTemplate(item));
}
});
});

最新更新