首页 > 技术文章 > tp5(laravel7) ajax模型修改数据

xiaoyantongxue 2021-10-29 14:29 原文

 

① 设置ajax请求(10分)

② 后台更改数据值(10分)

③ 重新计算平均分(10分)

④ 无刷新更新评分结果(10分)

思路:

在详情页面中有一个评分的按钮,单击后进行修改数据,首先找见本条数据的主键id,通过ajax 将id和修改的参数值传递到后台控制器中,再去模型进行修改数据。

 

 代码:模型中提取数据,发送至视图进行循环渲染

模型代码

<?php namespace app\day29\model; use think\Model; class CompanyModel extends Model { // protected $table = "day29"; //数据查询 public static function listInfo() { return self::paginate(6); } }

 

控制器代码:
<?php

namespace app\day29\controller;

use app\day29\model\CompanyModel;
use think\Controller;
use think\Request;

class Company extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //调取模型的数据
        $data=CompanyModel::listInfo();
//        将数据发送至页面
        $this->assign('data',$data);
        return  view();

    }
}
视图代码:
<!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>
<table class="table">

<tr>
    <td>企业名称</td>
    <td>企业评分</td>
    <td>操作</td>
</tr>

    {foreach $data as $item}
    <tr>
        <td>{$item.name}</td>
        <td>{$item.score}</td>
        <td><a href="/day29/company/edit/id/{$item.id}">详情</a></td>
    </tr>
    {/foreach}
</table>
{$data->render()}
</body>
</html>

以上是代码和效果。

接下来就是点击详情后的功能实现,单击详情后将本条数据的id传至控制器

 

控制器代码
    public function edit($id)
    {
        //接受id,并验证id
       if (!intval($id)){
           $this->error('id错误','/day29/company/index');
       }
//      根据id提取模型中的数据
       $details=CompanyModel::details($id);
//       发送视图至数据,并渲染
       $this->assign('details',$details);
       return  view();

    }
模型代码:
//详情查询
    public static function details($id)
    {
        return self::find($id);

    }
视图代码
<!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 class="table-responsive">
    <table class="table">
        <caption>详情</caption>

        <tr>
            <td>企业名称</td>
            <td>企业评分</td>
        </tr>
        <tr>
            <th>{$details.name}</th>
            <th>{$details.score}</th>
        </tr>
    </table>
</div>

<form action="" method="get">
    <input type="hidden" name="id" value="{$details.id}" class="getId">
    <p>评分:</p>
    <input type="radio"  name="score" value="10">10分
    <input type="radio"  name="score" value="8">8分
    <input type="radio"  name="score" value="6">6分
    <input type="radio"  name="score" value="4">4分
    <input type="radio"  name="score" value="2">2分
    <input type="button" value="评分" class="btn btn-success test">
</form>
</body>
</html>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">
</script>
<script>
    $('.test').click(function (){
    //  获取数据
      var score=$('input[name=score]:checked').val();
        var id=$('.getId').val();

      $.ajax({
          url:"http://www.day.com/day29/company/update",
          method:"PUT",
          data:{
              score:score,
              id:id
          },
          dataType:"JSON",
          success:function (res){
            alert(res.message)
          }

      })


    })


</script>

效果图:

 

 接下来的修改的重点,选中单选按钮,点击评分按钮,即可修改评分

 

 

 

 

控制器代码,接受ajax的参数,发送至模型进行修改

 public function update(Request $request,$id)
    {
        //
       $data=$request->put();
        $id=$data['id'];
       $res=[
           'score'=>$data['score']
       ];
       $res=CompanyModel::updata($res,$id);
       if (!$res){
           return  json(['code'=>500,'data'=>$res,'message'=>'更新失败']);
       }else{
           return  json(['code'=>200,'data'=>$res,'message'=>'更新成功']);
       }
       
    }

模型代码:

//修改
    /* 更新数据
    * @access public
    * @param array      $data  数据数组
    * @param array      $where 更新条件
    * @param array|true $field 允许字段
    public static function update($data = [], $where = [], $field = null)
    */
    public static function updata($res, $id)
    {
        return self::update($res, ['id' => $id], true);

    }

模型易错点

 

 控制器易错点

 

laravel实现以上功能:

 

 

 

① 设置ajax请求(10分)

② 后台更改数据值(10分)

③ 重新计算平均分(10分)

④ 无刷新更新评分结果(10分)

html:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="http://apps.bdimg.com/libs/bootstrap/3.3.0/css/bootstrap.min.css">
</head>
<body>

<table class="table">
    <tr>
        <td>id</td>
        <td>企业名称</td>
        <td>企业评分</td>
    </tr>
    <tr>
        <td id="id" >{{$info->id}}</td>
        <td>{{$info->name}}</td>
        <td id="divide">{{$info->divide}}</td>
    </tr>
</table>

<form action="" method="">
    <input type="hidden" name="id"  value="{{$info->id}}">
    <input type="radio" name="divide" value="10分">10分
    <input type="radio" name="divide" value="8分">8分
    <input type="radio" name="divide" value="6分">6分
    <input type="radio" name="divide" value="4分">4分

<button type="button" id="sub">提交</button>
</form>

</body>
</html>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script src="/static/js/layer/layer.js">
</script>
<script>
    $('#sub').click(function () {
        var divide= $("input[type='radio']:checked").val()
        var id= $("#id").text()
                $.ajax({
            url: '/day3/fraction',
            type: 'POST',
            data: {
                divide,
                id
            },
            dataType: 'JSON',
            success: function (res) {

                if (res.code == 200) {
                  //替换值,实现无刷新更新评分结果
                    $('#divide').text(res.data)
                    layer.msg('修改成功!', {icon: 1, time:3000});
                                 
                } else {
               
                    layer.msg('修改失败!', {icon: 2, time:3000});
                }
            }
    })

    })



</script>

路由:

Route::group(['namespace'=>'Day3'],function (){
//    修改分值
    Route::post('day3/fraction','ExamController@fraction')->name('day3.fraction');

});

控制器代码:

    public function fraction(Request $request){
//        接值
        $fraction=$request->post();
//        修改分值
       $res= Day::where('id','=',$fraction['id'])->update(['divide'=>$fraction['divide']]);
       if (!$res){
           return ['code'=>500,'message'=>'error','data'=>''];
       }
//       找见字段值,并将值传递给后台,前端进行替换即可
       $divide=Day::find($fraction['id'])->divide;
        return ['code'=>200,'message'=>'success','data'=>$divide];
    }
}

 

推荐阅读