tp5与ajax交互增加数据
使用tp5框架
1.首先在config-database中配置好数据库
2.在app\index下创建model文件夹,创建User.php文件
<?php
namespace app\index\model;
use think\Model;
class User extends Model{
//使用的表名
protected $table='user';
//表的主键
protected $pk='id';
}
?>
3.在app\index下创建view文件夹,并创建index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="/static/js/jquery.min.js"></script>
</head>
<body>
<input type="text" name="username" id="username"/>
<input type="text" name="password" id="password"/>
<input type="submit" id="insert" value="添加" />
<script>
$('#insert').click(function(){
var data = {
'username':$('#username').val(),
'password':$('#password').val()
};
$.ajax({
type:"post",
url:'add',
data:data,
success:function(data){
console.log(data.msg);
if(data.reg==1){
alert(data.msg);
}else{
alert(data.msg);
}
},
error:function(data){
console.log(data.msg);
}
});
})
</script>
</body>
</html>
2.在app\index\controller下创建index文件,创建User.php文件
<?php
namespace app\index\controller;
use app\index\model\User;
use think\Controller;
use think\facade\Request;
class Index extends Controller
{
public function index()
{
return $this->fetch();
}
public function add()
{
$data = Request::param();
//查找此人是否存在
$res = User::where('username',$data['username'])->find();
//如果存在返回提示信息
if($res){
return ['reg'=>0,'msg'=>'已存在'];
}
//创建user model对象
$user = new User();
//添加姓名
$user->username=$data['username'];
//添加密码
$user->password=$data['password'];
//添加时间戳
$user->time=time();
//保存数据
if($user->save())
{
return ['reg'=>1,'msg'=>'添加成功'];
}else
{
return ['reg'=>0,'msg'=>'添加失败'];
}
}
}