首页 > 解决方案 > 分数验证在 Laravel 中表现异常

问题描述

在我的 Laravel-5.8 应用程序中,我有以下代码:

public function findScore(Request $request)
{
    $userCompany = Auth::user()->company_id;
    $userEmployee = Auth::user()->employee_id;
    
    $identities                     = DB::table('identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first()->id;      

   $weightedscore = 0;
   $weightedscore = DB::table('goals')->select(DB::raw("IFNULL(SUM(weighted_score),0) as weighted_score"))->where('identity_id', $identities)->where('employee_id', $userEmployee)->where('parent_id', $parentid)->whereNull('deleted_at')->first();
   $weightedscorex = 0;

   $maxscore = DB::table('goal_types')->select('max_score')->find($child->parent_id);

    return response()->json([
        'maxscore' => $maxscore->max_score,
        'weightedscore' => $weightedscore->weighted_score,
    ]);        
}

路线:

Route::get('get/findScore','GoalsController@findScore')->name('get.scores.all');

查看(create.blade.php)

          <div class="col-12 col-sm-6">
            <div class="form-group">
              <label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
              <select id="goal_type" class="form-control @error('goal_type_id') is-invalid @enderror" name="goal_type_id">
              <option value="">Select Goal Type</option>

                @foreach ($categories as $category)
                @unless($category->name === 'Job Fundamentals')
                  <option hidden value="{{ $category->id }}" {{ $category->id == old('goal_type_id') ? 'selected' : '' }}>{{ $category->name }}</option>

                  @if ($category->children)
                    @foreach ($category->children as $child)
                    @unless($child->name === 'Job Fundamentals')
                      <option value="{{ $child->id }}" {{ $child->id == old('goal_type_id') ? 'selected' : '' }}>&nbsp;&nbsp;{{ $child->name }}</option>
                    @endunless
                    @endforeach
                  @endif
                  @endunless
                @endforeach
              </select>

    <input type="hidden" id="max_score" class="form-control" >
    <input type="hidden" id="weighted_score" value="0" class="form-control" >


          <div class="col-12 col-sm-6">
            <div class="form-group">
              <label class="control-label"> Weight(%):<span style="color:red;">*</span></label> 
              <input  type="text" name="weighted_score" id="total_weighted_score" value="{{ old('weighted_score', $goal->weighted_score) }}" placeholder="Enter weighted score here" class="form-control @error('weighted_score') is-invalid @enderror" max="120" onkeyup="checkScore(this.value)">
            </div>
          </div>  

    <div class="card-footer">
      <button type="submit" class="btn btn-primary">Save</button>
    </div>           

Javascript

    <script type="text/javascript">
    $(document).ready(function() {
        $(document).on('change', '#goal_type', function() {
            var air_id =  $(this).val();

            var a = $(this).parent();
            var op = "";
            
            $.ajax({
                type: 'get',
                url: '{{ route('get.scores.all') }}',
                data: { 'id': air_id },
                dataType: 'json',      //return data will be json
                success: function(data) {
                    console.log(data.maxscore);
                    console.log(data.weightedscore);
                     $('#max_score').val(data.maxscore);
                     $('#weighted_score').val(data.weightedscore);
                },
                error:function(){

                }
            });
        });
    });
    </script>
    <script type="text/javascript">
        function checkScore(value){
            let max_score = $("#max_score").val();
            let weighted_score = $("#weighted_score").val();
            let sumValue = parseInt(weighted_score) + parseInt(value);

            if (sumValue > max_score) {
              alert("sum value is greater than max score");
              $("#total_weighted_score").val('');
              return false;
            }
        }
    </script>

在使用 id="goal_type" 选择下拉更改时,我加载了所选目标类型的 max_score。
onkeyup="checkScore(this.value)" 用于验证累计加权分数是否大于 max_score。如果是,那么它会发出警报:

alert("总和值大于最高分");

这在大多数情况下都非常有效。但是,我发现验证不稳定。有时它不起作用。即使累积的加权分数小于 max_score 也会引发警报问题发生在各种情况下。但有时当用户尝试在文本输入中输入值而不选择下拉菜单时。

我该如何解决这个问题?

标签: javascriptlaravel

解决方案


这不一定是最佳解决方案,但应该可以解决您的问题。如果 ajax 尚未返回您的值,但只需以不会触发您的错误的方式初始化它们。

function checkScore(value) {
    let max_score = $("#max_score").val();
    max_score = max_score ? parseInt(max_score) : Number.MAX_SAFE_INTEGER;

    let weighted_score = $("#weighted_score").val();
    weighted_score = weighted_score ? parseInt(weighted_score) : 0;
    
    let sumValue = weighted_score + parseInt(value);
    
    if (sumValue > max_score) {
        alert("sum value is greater than max score");
        $("#total_weighted_score").val('');
        return false;
    }
}

推荐阅读