批改状态:合格
老师批语:
本实例主要练习Ajax()方法的用法
$.ajax()是jQuery中Ajax底层方法,$.get()和$.post()是它的特例。
主要参数有:
url:请求的服务器资源(必须是字符串)
type:客户端的请求类型,比如:'GET','POST',等等
dataType:从服务器返回的数据类型,比如:xml,html,json,txt等等
async:数据传输方式,true异步,false同步
data:向服务器发送的数据
1.查询字符串键值对 键=值&键=值......
2.json格式 {键:值,键:值,,,,,,}
3. 将表单元素值序列化为键值对 用 serialize()
4.将表单元素值序列化为json格式 用serializeArray()
success:成功回调
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用ajax()方法实现表单元素无刷新验证</title>
</head>
<body>
<form style="width:600px">
<fieldset>
<legend>用户登录</legend>
<label>用户名:<input type="text" name="name"></label>
</fieldset>
</form>
</body>
</html>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(':input').blur(function(){
$.ajax({
url: 'api/demo.php',
type: 'GET',
async: true,
// data: 'name='+$(':input').val(),
// data: {'name':$(':input').val()},
// data: $('form:first').serialize(),
data: $(':input').serializeArray(),
success: function(msg) {
$('label span').empty()
$('label').append($(msg))
}
})
})
</script>点击 "运行实例" 按钮查看在线实例
服务器端php代码(引用朱老师代码)
<?php
$nameList = ['admin','tsmax','www'];
$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>';
}点击 "运行实例" 按钮查看在线实例
$.ajax()练习手写代码

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号