批改状态:合格
老师批语:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>7.$.ajax()</title>
</head>实例
<?php
// print_r($_GET['name']);exit;
// 用数组来模拟数据库中已经存在的用户名,这些用户名是禁止使用的
$nameList = ['admin','huodi','huodi100'];
//当前用户提交的用户名
$userName = $_GET['name'];
//判断用户名是否为空
if(strlen(trim($userName)) == 0) {
$status = 0;
$tips = '<span style="color:red">用户名不能为空</span>';
echo json_encode(['status'=>$status,'tips'=>$tips]);
}
//判断是否为纯数字
else if (is_numeric($userName)) {
$status = 0;
$tips = '<span style="color:red">用户名不能纯数字</span>';
echo json_encode(['status'=>$status,'tips'=>$tips]);
}
//判断是否已存在
else if (in_array($userName,$nameList)) {
$status = 0;
$tips = '<span style="color:red">用户名已存在</span>';
echo json_encode(['status'=>$status,'tips'=>$tips]);
}
//用户名可用的提示
else {
$status = 1;
$tips = '<span style="color:green">恭喜,用户名可用</span>';
echo json_encode(['status'=>$status,'tips'=>$tips]);
}
运行实例 »
点击 "运行实例" 按钮查看在线实例
<body>
<h2>用户登录</h2>
<form>
<p>用户名:<input type="text" name="name"></p>
</form>
</body>
</html>
<script type="text/javascript" src="./js/jquery.js"></script>
<script type="text/javascript">
/**
* $.ajax()
* 功能:是jquery中的ajax的底层方法,$.post(),$.get()是它的快捷函数
* 语法:$.ajax(type,url,dataType,success,error)
* 参数:参数通常写到js对象字面量中
*/
$(':input').blur(function(){
//语法1:将回调函数写到$.ajax()函数中
//
//序列化:name=admin&password=123456$age=30&sex=0&hoppy......
//
$.ajax({
//1.请求的服务器资源
url:'./api/demo.php',
//2.客户端的请求类型:get,post,put...
type:'GET',
//3.从服务器返回的数据格式:json,html,xml,text
// dataType:'json',
//4.异步或同步,true异步,false同步(浏览器锁定)
async:true,
//5.发送的数据:string,json,序列化
//查询字符串
// data:'name='+$(':input').val(),
// data:{'name':$(':input').val()},
// data:$('form:first').serialize(), //结果是查询字符串
data:$('form:first').serializeArray(), //以json方式发送的
//6.成功回调函数:success:function(msg){}
success:function(msg,status,xhr){
console.log(msg)
$('p span').empty()
$('p').append($(msg))
//$('span').append($(msg))
}
//7.错误回调函数:error:function(xhr,status,error){}
})
/**
// $.ajax()第二种语法格式,用的不多,但要看得懂!
$.ajax({
url:'api/demo1.p实例
<?php
// print_r($_GET['name']);exit;
// //用数组来模拟数据库中已经存在的用户名,这些用户名是禁止使用的
$nameList = ['admin','huodi','huodi100'];
// //当前用户提交的用户名
$userName = $_GET['name'];
//判断用户名是否为空
if (strlen(trim($userName)) == 0) {
echo '<span style="color:red">用户名不能为空</span>';
}
//判断用户名是否为纯数字
elseif (is_numeric($userName)) {
echo '<span style="color:red">用户名不能为纯数字</span>';
}
//判断用户名是否重复
elseif (in_array($userName, $nameList)) {
echo '<span style="color:red">用户名已存在</span>';
}
//用户可用提示
else {
echo '<span style="color:green">恭喜,用户名可用</span>';
}
运行实例 »
点击 "运行实例" 按钮查看在线实例hp',
type:'GET',
dataType:'json',
data:$('form:first').serialize()
}).done(function(msg){ //成功的回调
console.log(msg.tips)
$('p span').empty()
$('p').append($(msg.tips))
})*/
})
</script>点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号