注:该实例需要在php环境运行
目录结构如下图:
先看页面部分,html代码如下:
<body>
<div id="container">
<div id="main">
<h1>请输入用户名输入数据</h1>
</div>
<div id="contorll">
<input type="text" id="uname">
<button>请求</button>
</div>
</div>
<script src="demo.js"></script>
</body>
接下来是样式:
body{
min-height: 100vh;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
}
*{
font-family: Arial, Helvetica, sans-serif;
}
h1{
font-weight: normal;
}
h1 span{
color: #c0010a;
}
#container{
display: flex;
flex-direction: column;
width: 360px;
justify-content: center;
align-items: center;
}
#main{
height: 360px;
border: 1px solid #ccc;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
background-size: cover;
}
#contorll{
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 30px;
}
#contorll input{
flex: 1;
height: 36px;
border: 1px solid #d8d8d8;
border-radius: 4px;
outline: none;
padding: 0 16px;
}
#contorll button{
height: 36px;
cursor: pointer;
background: #2c83f5;
cursor: pointer;
border: none;
border-radius: 4px;
padding: 0;
margin-left: 10px;
width: 100px;
color: #fff;
}
页面效果:
js部分,demo.js:
let main = document.querySelector('#main') //获取到页面元素
let btn = document.querySelector('button') //获取按钮
btn.addEventListener('click', function () { //按钮点击事件
let uname = document.querySelector('#uname').value //拿到输入的值
let xhr = new XMLHttpRequest()
xhr.open('get',`demo.php?uname=${uname}`) //ajax发送get请求并传递参数
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
let res = JSON.parse(xhr.responseText);//后端返回请求结果
if (res.url) {
main.innerHTML = `<h1>欢迎您,<span>${res.uname}</span></h1>`;
main.style.backgroundImage = `url(${res.url})`
} else {
main.style.removeProperty('background-image');
main.innerHTML = `${res.msg}`;
}
}
}
}
})
后端逻辑代码demo.php:
<?php
// 允许跨域
header('Access-Control-Allow-Origin:*');
$uname = $_GET['uname'];
$user_arr = array('JAY','JAMES','JORDAN');//创建搜索关键词数组,模拟匹配搜索结果
if(isset($uname)){
if(in_array($uname,$user_arr)){
if($uname == 'JAY'){ //如果匹配到就返回搜索名和背景图
echo json_encode(array(
'uname' => $uname,
'url' => 'images/bg1.jpeg'
));
}elseif($uname == 'JORDAN'){
echo json_encode(array(
'uname' => $uname,
'url' => 'images/bg2.jpeg'
));
}elseif($uname == 'JAMES'){
echo json_encode(array(
'uname' => $uname,
'url' => 'images/bg3.jpeg'
));
}
}else{
//匹配不到返回提示信息
echo json_encode(array(
'msg' => '<h1>sorry,没有<span>'.$uname.'</span>的信息</h1>'
));
}
}
?>
下图演示最终效果