<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax--GET</title>
</head>
<body>
<p>
<label for="user_id">输入用户ID</label>
<input type="text" id="user_id" name="user_id" autofocus>
</p>
<p id="tips"> </p>
<script>
// 抓元素
var input = document.getElementById('user_id');
var tips = document.getElementById('tips');
//创建请求参数
var request = new XMLHttpRequest();
// console.log(request);
// 给input添加键盘事件
input.onkeypress = function (ev) {
// console.log(ev.key);
if (ev.key === 'Enter'){
if (input.value.length ===0){
tips.innerHTML = '不能为空';
} else if (isNaN(input.value)){
tips.innerHTML = '请输入正确的整数'
} else{
//2、 成功回调
request.onreadystatechange = function (ev) {
if (request.readyState === 4){
tips.innerHTML = request.responseText;
}
}
// 3、设置请求参数
var data = encodeURIComponent(input.value);
request.open('GET','user_info.php?user_id='+data,'true')
// 4、发送异步请求
request.send(null);
}
}
}
input.oninput = function(){
tips.innerHTML = null;
} </script>
</body>
</html>
// 下面是用到的user_id.php文件
<?php
$userId = isset($_GET['user_id']) ? $_GET['user_id'] : null;
$userInfo = [
['user_id'=>1, 'username'=>'苍老师', 'gender'=>'女', 'age'=>26],
['user_id'=>2, 'username'=>'波老师', 'gender'=>'女', 'age'=>23],
['user_id'=>3, 'username'=>'黑老师', 'gender'=>'男', 'age'=>33],
];
$res = '';
foreach ($userInfo as $user) {
if ($user['user_id'] === intval($userId)) {
$res .= $user['user_id'].'---'.$user['username'].'---'.$user['gender'].'---'.$user['age'];
}
}
echo empty($res) ? '<span style="color: red;">没有找到该用户名</span>' : $res;
exit;