ajax 无刷新页面登录

1:页面代码

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="http://apps.bdimg.com/libs/bootstrap/3.3.0/css/bootstrap.min.css">
</head>
<body>
<div style="width: 300px">
    <div class="form-group">
           <label for="name">名称</label>
        <input type="text" class="form-control account" name="account"   >
    </div>
    <div class="form-group">
        <label for="name">密码</label>
        <input type="password" class="form-control password" name="password"   >
    </div>
    <input type="hidden" name="__token__" value="{$Request.token}" />
    <input type="button"  id="login" value="立即登录">
</div>
</body>
</html>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
    $('#login').click(function (){
        var account =$('.account').val();
        var password=$('.password').val();
        $.ajax({
            url:'/ajax/ajax/save',
            type:'POST',
            data:{
                account:account,
                password:password,
                __token__:"{$Request.token}",
            },
            dataType:'json',
            success:function (res){
                // console.log(res)
          if (res.code==200){
              alert('登录成功');
              //将用户res里的Token存入在本地
              localStorage.setItem('token','res.data.token')
              location.href='/ajax/ajax/index';
          }
            }
        })

    })




</script>

2:控制器代码

 

 

 

<?php

namespace app\ajax\controller;

use app\ajax\model\AjaxModel;
use think\Controller;
use think\Request;
use think\Session;
use think\View;
use tools\jwt\Token;

class Ajax extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //展示登录后首页
    return \view();
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //展示登录页面
        return view();
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
        $params = $this->request->post();
        //验证user表是否与用户输入的信息向匹配
        $data = AjaxModel::getLogininfo($params);
        if ($params['account'] != $data['username']) {
            $this->error('账号输入错误', '/ajax/ajax/create');
        }
        if ($params['password'] != $data['userpassword']) {
            $this->error('密码输入错误', '/ajax/ajax/create');
        }
     return json(['node'=>200,'massage'=>'success','data'=>$data]);
      
    }

3:模型代码

<?php

namespace app\ajax\model;

use think\Model;

class AjaxModel extends Model
{
    //查询user用户表
    protected $table = 'user';

    public static function getLogininfo($params)
    {
        return self::where('username', $params['account'])->find();
    }
}

 

posted @ 2021-08-27 21:52  王越666  阅读(39)  评论(0编辑  收藏  举报