批改状态:合格
老师批语:
使用$.ajax()做一个输入用户名的检测
页面预览如下:

原HTML代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>$.ajax()的使用方法</title>
<style type="text/css">
.box1{
background-color: lightgreen;
width: 400px;
height: auto;
margin:30px;
padding: 30px;
}
#yong{
margin-left: 50px;
}
</style>
</head>
<body>
<div class="box1">
<form>
<h2 id="yong">用户注册</h2>
<p>用户名:<input type="text" name="name"></p>
</form>
<button>查询</button>
</div>
</body>
</html>
<script type="text/javascript" src="../ajax/js/jquery.js"></script>
<script type="text/javascript">
/**
* $.ajax()
* 功能:是jquery中的Ajax底层方法,之前学过的$.get(),$.post...都它的特殊形式
* 语法: $ajax()
* 参数: 参数写到js对象字面量中
* 注:因参数众多,下面用实例进行说明
*/
//点击查询进行查找验证
$('button').click (function(){
// alert('通过')
//使用ajax进行异步验证
//语法1: 全部参数写到$.ajax()参数中
$.ajax({
//请求的服务器资源,必须是字符串
url: '../ajax/api/info.php',
//客户端的请求类型:GET,POST...,推荐大写
type: 'GET',
data: $('form:first').serializeArray(),
//成功回调
success: function(msg,status,xhr) {
console.log(msg)
$('p span').empty()
$('p').append($(msg))
}
})
})
//$.ajax()第二种语法格式,用得不多,但要看得懂
// $.ajax({
// url: 'api/demo1.php',
// type: 'GET',
// dataType: 'json',
// data: $('form:first').serialize(),
// })
// .done(
// function(msg) {
// console.log(msg.tips)
// $('p span').empty()
// $('p').append($(msg.tips))
// })
</script>点击 "运行实例" 按钮查看在线实例
PHP代码如下:
<?php
// print_r($_GET);exit;
// 用数组模拟数据库中的已存在的用户名,这是不允许使用的
$nameList = ['admin','peter','php'];
//这是当前用户提交的用户名
$userName = $_GET['name'];
//判断用户名是否为空
if (strlen(trim($userName))==0) {
echo '<span style="color:red">用户名不能为空</span>';
//判断用户名是否为纯数字,这是不允许的
} else if (is_numeric($userName)) {
echo '<span style="color:red">用户名不能为纯数字</span>';
//判断用户名是否已经被注册
} else if (in_array($userName, $nameList)) {
echo '<span style="color:red">用户名太抢手了,换一个</span>';
//用户名可用提示
} else {
echo '<span style="color:green">恭喜,用户名可用</span>';
}点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号