<body>
<div>
<input type="text">
<button>search</button>
</div>
<ul></ul>
<script>
var input = document.querySelector("input");
var btn = document.querySelector("button");
var ul = document.querySelector("ul");
btn.onclick = function(){
var value = input.value.trim();
if(!value){
alert('不能为空');
}
var xhr = new XMLHttpRequest();
xhr.onload = function(){
if(xhr.status == 200){
var res = JSON.parse(xhr.responseText);
if( res.status == 0 ){
var tmp = res.data.map(function(v,i){
return `
<li>
<h3>${v.className}</h3>
<p>${v.classInfo}</p>
<p>${v.classTime}</p>
</li>
`;
}).join('');
ul.innerHTML = tmp;
}
else{
ul.innerHTML = '查无数据';
}
}
}
xhr.open('GET','search.php?searchWord='+value,true);
xhr.send(null);
}
</script>
</body>
<?php
@$con = mysqli_connect('localhost','root','','shirleytest');
header('content-type:text/html;charset=utf-8');
mysqli_query($con,'set names utf8');
$searchWord = $_GET['searchWord'];
$sql = "select * from course where className like '%{$searchWord}%'";
$query = mysqli_query($con,$sql);
if($query && mysqli_num_rows($query) ){
while($row = mysqli_fetch_assoc($query)){
$arr[] = $row;
}
echo '{"status":0,"msg":"ok" , "data" : '.json_encode($arr).'}';
}else{
echo '{"status": -1 , "msg":"error" , "data" : [] }';
}
?>