Php学习Day03- Layui之Ajax测试
环境
- layui-v2.4.5
- ThinkPHP 5.0.*
- Gif生成小公举:https://www.cockos.com/licecap/licecap128-install.exe
说明
一直比较喜欢layui的简洁性,尝试了下,但是仅仅这个layui的ajax提交就让我费了2天时间,真实郁闷之极。今天终于搞定,留个脚印,记下来…
开始
form代码:
代码说明:
- 主要关注form标签以及button标签,注意class和 lay-filter。详见代码:class="layui-form"和lay-filter=“demo1” 。
<form class="layui-form" action="" id="myform" enctype="multipart/form-data" method="POST">
<input type="number" name="teacherId" hidden value="{$Think.session.teacherid}">
姓名:<input type="text" name="name">
<input type="button" name="btnSearch" value="查询">
<!--<a href="javascript:;"><button class="layui-btn" onclick="submitform()">查询</button></a>-->
<button class="layui-btn" lay-submit="" lay-filter="demo1" style="float: right;margin: 20px">查询</button>
<div class="mt-20">
<table class="table table-border table-bordered table-hover table-bg table-sort">
<thead>
<tr class="text-c">
<th width="50">ID</th>
<th width="50">姓名</th>
<th width="30">性别</th>
<th width="30">年龄</th>
<th width="90">手机号</th>
<th width="150">邮箱</th>
<th width="100">入学时间</th>
<th width="160">班级</th>
<th width="50">状态</th>
<th width="100">操作</th>
</tr>
</thead>
<tbody>
{volist name='list' id='vo'}
<tr class="text-c">
<td>{$vo.id}</td>
<td>{$vo.name}</td>
<td>{$vo.sex}</td>
<td>{$vo.age}</td>
<td>{$vo.mobile}</td>
<td>{$vo.email}</td>
<td>{$vo.start_time}</td>
<td class="td-manage">
</td>
</tr>
{/volist}
</tbody>
</table>
</div>
</form>
js 脚本
- 其中需要声明:var $=layui.jquery,和form = layui.form ;
- 监听按钮事件中注意“demo1”就是button的lay-filter属性值"demo1" ;
- 下面的和jquery的ajax一样,注释的脚本可以查看提交的一些信息。
- 其中layer.msg用法备注下:
layer.msg(“文字!”, {icon:6, time:1000}, function(){ layer.msg(“关闭后想做些什么”); });
<script>
layui.use(['form', 'layer','layedit', 'laydate','upload'], function() {
var $=layui.jquery,
form = layui.form;
console.log('--start---');
// 监听按钮
form.on('submit(demo1)', function(data){
// layer.alert(JSON.stringify(data.field), {
// title: '最终的提交信息'
// })
// return false;
$.ajax({
url:"{:url('index/ajaxTest')}",
method:'post',
data:data.field,
dataType:'JSON',
success:function(data){
console.log('--msg---');
// layer.alert(JSON.stringify(data), {
// title: '最终的提交信息'
// })
if(data.status==1){
// layer.msg(data.msg, {icon:6});
layer.msg("保存成功!", {icon:6, time:1000}, function(){
layer.msg("关闭后想做些什么");
// location.href=location.href;//刷新页面
});
} else {
layer.msg(data.msg,{icon:5});
}
},
error:function (data) {
layer.msg(data.msg,{icon:5});
}
})
return false;
});
});
</script>
PHP脚本
// 渲染ajaxtest页面
public function ajax()
{
return $this-> view ->fetch('ajax');
}
// 调用ajaxTest方法
public function ajaxTest(Request $request)
{
$status = 1;
$msg = "a ajax test";
return ['status'=>$status, 'msg'=>$msg];
}
最后的效果如下: