前端部分
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax</title>
<style>
*{
padding: 0;
margin: 0;
}
ul li{
list-style-type: none;
}
.wrap{
width: 100%;
padding: 30px;
}
.input-wrap{
position: relative;
margin: auto;
width: 424px;
}
.input-wrap .word{
padding:10px;
outline: 0 none;
width: 400px;
}
.word-result-list{
display: none;
position: absolute;
top: 39px;
left: 0;
padding: 12px;
width: 398px;
min-height: 200px;
border: 1px solid #ddd;
}
</style>
</head>
<body>
<div class="wrap">
<div class="input-wrap">
<form action="">
<input type="text" id="word-id" name="word" class="word" />
</form>
<ul class="word-result-list" id="word-result-list">
</ul>
</div>
<p id="text"></p>
</div>
<script>
var wordInput = document.getElementById('word-id');
var wordResultList = document.getElementById('word-result-list');
var text = document.getElementById('text');
wordInput.onfocus = function(){
showResultLists();
}
wordInput.oninput = function(){
showResultLists();
ajax(this.value);
}
wordInput.onblur = function(){
hideResultLists();
}
function showResultLists(){
if(wordInput.value){
wordResultList.style.display = 'block';
}else{
wordResultList.style.display = 'none';
}
}
function hideResultLists(){
wordResultList.style.display = 'none';
}
function ajax(str){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var data = JSON.parse(xmlhttp.responseText);
wordResultListData(data);
}
}
xmlhttp.open("POST","data.php?t="+Math.random(),true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //设置响应头
xmlhttp.send("inputWord="+wordInput.value); //POST数据提交
}
function wordResultListData(data){
if(data.length>0){
var i = 0;
var len = data.length;
//清空ul里的数据
wordResultList.innerHTML = "";
for(; i<len; i++){
var newNode = document.createElement("li");
newNode.innerHTML = data[i];
wordResultList.appendChild(newNode);
}
}
}
</script>
</body>
</html>
后台部分
<?php
header("Content-type: text/html; charset=utf-8");
$data = ["广东","广西","山西"];
$result = [];
//echo json_encode($data);
foreach ($data as $key => $value) {
if( strpos($value,$_POST['inputWord']) !== false ){ //如果存在
array_push($result,$value);
}
}
echo json_encode($result);
?>
网友评论