使用console.log可以看到正确的结果,但是当我尝试在搜索框下方创建的跨度中显示结果时,
HTML:
<form method="GET" action="recherche.php" class="form ml-auto" autocomplete="off">
<input id="search" name="search" class="form-control mb-1" type="text" placeholder="Search" aria-label="Search">
//This is where I want the results displayed
<span class="search-results"></span>
<button value="Soumettre" class="btn btn-primary" type="submit">Rechercher</button>
</form>
CSS:
.search-results{
display:block;
position:absolute;
background-color:#fff;
border:1px solid black;
padding:10px 20px;
z-index:10;
}
Javascript:
var valueText = document.getElementById('search');
var resultsSpan = document.getElementsByClassName('search-results');
var form = document.querySelector('search');
xhr = new XMLHttpRequest()
valueText.addEventListener('keyup' , function(){
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4){
if(xhr.status == 200){
var resultat = [];
resultsSpan.className + 'search-results'
console.log('this.responseText', this.responseText)
console.log('resultsSpan', resultsSpan)
var results = JSON.parse(this.responseText)
for (let i=0; i<results.length; i++){
resultat.push('<li>' + results[i].titre + '</li>');
}
resultsSpan.innerHTML = resultat;
}else{
console.log('Error' , xhr.statusText)
}
}
}
xhr.open("GET", "search.php?search=" + valueText.value, true);
xhr.send(null);
});
谢谢。