所以,我正在制作一个动态搜索栏,一切都按照预期工作(从Django获取结果,将其转换为JSON, JS接收JSON等),除了将结果转换为页面上的HTML。我不确定我应该怎么做才能让结果显示在网页上,而不仅仅是在控制台上?
代码:
<form class="d-flex" method="POST">
{% csrf_token %}
<input class="form-control me-2" type="search" id='search' placeholder="Search for books via their titles" aria-label="Search" >
<div id="results" style="display: none;">
</div>
</form>
document.addEventListener("DOMContentLoaded", () => {
// TODO: Implement Search Mechanic
const search = document.querySelector("#search");
if (search !== null)
{
search.onkeyup = () => {
console.log(search.value);
get_results(search.value);
};
}
});
function get_results(query)
{
//TODO Create API to get results
if (query === null)
{
return []
}
if (query !== "")
{
fetch(`/results/${query}`)
.then(response => response.json())
.then(result => {
console.log(result);
const display_div = document.querySelector("#results");
display_div.style.display = "block";
result.forEach(query => {
console.log(query);
const par = document.createElement("par");
const a = document.createElement("a");
a.classList.add = "links";
a.textContent = query.name;
a.href = "#";
par.appendChild(a);
display_div.appendChild(par);
});
});
}
}
@login_required
def results(request, query):
if request.method == "GET":
if query is not None:
results = Search(query).get_results()
print(results)
JsonResponse({"message": f"query {query} successful"}, status=200)
response = serializers.serialize("json", results)
return HttpResponse(response, content_type='application/json')
par不是一个有效的HTML标签。
您是否检查了您的dom,是否有任何附加内容?
除了像下面这样更改search.js之外,我还将表单和div移出了它们所在的导航栏。现在一切正常。
document.addEventListener("DOMContentLoaded", () => {
const search = document.querySelector("#search");
const display_div = document.querySelector("#results");
if (search !== null)
{
search.onkeyup = (e) => {
display_div.style.display = "none";
if (e.key !== " " || e.key !== "Enter")
{
get_results(search.value);
}
};
document.addEventListener("click", (e) => {
if (e.target !== 'a.nav-link') {
display_div.style.display = "none";
}
});
}
});
function get_results(query)
{
if (query === null || query.length < 3)
{
return []
}
if (query !== "")
{
fetch(`/results/${query}`)
.then(response => response.json())
.then(result => {
console.log(result);
const a = document.createElement("a");
const display_div = document.querySelector("#results");
display_div.innerHTML = "";
result.forEach(query => {
console.log(query);
a.setAttribute("class", "nav-link");
a.textContent = query.fields.name;
link = `book/view/${query.pk}`
a.href = `http://127.0.0.1:8000/${link}`;
a.onclick = () => {
window.location.href = `http://127.0.0.1:8000/${link}`;
};
display_div.appendChild(a);
});
display_div.style.display = "block";
});
}
}