0

在 laravel / jquery 应用程序中,如果我需要检查用户是否已登录,我会在控制器中进行:

$loggedUser = Auth::user();
if ( empty($loggedUser->id) ) {
    return response()->json(['error_code'=> 1, 'message'=> "You must be logged!"],HTTP_RESPONSE_INTERNAL_SERVER_ERROR);
}

因为我不需要让用户离开页面,而只限制一些功能,所以我使用 bootstrapGrowl 库在上面显示错误消息。现在使用 laravel 7 /livewire 1.3 / turbolinks:5 / alpine@v2 我搜索如何生成错误并显示类似的错误消息,让用户留在页面上?

更新 :

让我用详细的例子来解释一下:在 laravel / jquery 应用程序中我有 JS 代码:

var quiz_quality_radio= $('input[name=quiz_quality_radio]:checked').val()
var href = this_frontend_home_url + "/make-quiz-quality";
$.ajax( {
    type: "POST",
    dataType: "json",
    url: href,
    data: {"quiz_quality_id": quiz_quality_radio, "vote_id": this_vote_id, "_token": this_csrf_token},
    success: function( response )
    {
        $('input[name=quiz_quality_radio]:checked').prop('checked', false);
        frontendVote.showQuizQualityResults()
        popupAlert("Thank you for rating ! Your rate was added!", 'success')
    },
    error: function( error )
    {
        $('input[name=quiz_quality_radio]:checked').prop('checked', false);
        popupAlert(error.responseJSON.message, 'danger') // 'info', 'success'
    }
});

和控制中的相对动作:

public function make_quiz_quality(Request $request)
{
    $requestData     = $request->all();
    $quiz_quality_id = ! empty($requestData['quiz_quality_id']) ? $requestData['quiz_quality_id'] : '';
    $vote_id         = ! empty($requestData['vote_id']) ? $requestData['vote_id'] : '';

    if ( ! Auth::check()) {
        return response()->json(['message' => "To rate you must login to the system !"], HTTP_RESPONSE_BAD_REQUEST);
    }
    if (empty($quiz_quality_id)) {
        return response()->json([
            'message'         => "To rate you must select quiz quality !",
            'quiz_quality_id' => $quiz_quality_id
        ], HTTP_RESPONSE_OK);
    }

    $vote = Vote::find($vote_id);
    if ($vote === null) {
        return response()->json([ 'message' => "Vote Item # " . $vote_id . " not found !"],HTTP_RESPONSE_NOT_FOUND);
    }
    $loggedUser = Auth::user();

    $found_count = QuizQualityResult
        ::getByVoteIdAndUserId($vote_id, $loggedUser->id)
        ->count();
    if ($found_count > 0) {
        return response()->json(['message' => "You have already rated '" . $vote->name . "' # vote !", 'vote_id' => $vote_id],
            HTTP_RESPONSE_BAD_REQUEST);
    }

    $newVoteItemUsersResult = new QuizQualityResult();
    try {
        $newVoteItemUsersResult->quiz_quality_id = $quiz_quality_id;
        $newVoteItemUsersResult->vote_id         = $vote_id;
        $newVoteItemUsersResult->user_id         = $loggedUser->id;
        DB::beginTransaction();
        $newVoteItemUsersResult->save();

        DB::commit();
    } catch (Exception $e) {
        DB::rollBack();

        return response()->json(['message' => $e->getMessage(), 'voteCategory' => null], HTTP_RESPONSE_INTERNAL_SERVER_ERROR);
    }

    return response()->json(['message' => '', 'id' => $newVoteItemUsersResult->id], HTTP_RESPONSE_OK_RESOURCE_CREATED);
} //     public function make_quiz_quality(Request $request)

如果在错误块中生成错误,我会显示带有函数 popupAlert 的消息(用 bootstrapGrowl 实现),而不离开页面。这就是我想在 livewire / turbolinks / alpine 应用程序中制作的内容。我该怎么做?

更新#2:

这只是用户可以投票的项目列表:

<div class="table-responsive">
    <table class="table text-primary">
        @foreach($quizQualityOptions as $key=>$next_quiz_quality_option)
            <tr>
                <td>
                    <input class="" type="radio" name="quiz_quality_radio" id="quiz_quality_radio_{{ $next_quiz_quality_option }}" value="{{ $key }}">
                    <label class="col-form-label" for="quiz_quality_radio_{{ $next_quiz_quality_option }}">{{ $next_quiz_quality_option }}</label>
                </td>
            </tr>
        @endforeach
    </table>
</div>

<div class="row p-3">
    <a class="btn btn-primary a_link" onclick="javascript:frontendVote.MakeQuizQuality()">Rate !</a>
</div>

有2个限制:

  1. 用户必须登录
  2. 只有在服务器生成这 2 个错误后,任何登录用户才能投票。

更新#3:

我找到了使用 axios 的决定,例如:

    <button type="submit" class="btn btn-primary btn-sm m-2 ml-4 mr-4 action_link" @click.prevent="submitNewTodo()">
        Submit
    </button>



submitNewTodo() {
   console.log('submitNewTodo::')
    let is_insert= 1
    let current_toto_id= 1
    axios({
        method: (is_insert ? 'post' : 'patch'),
        url: '/api/todos' + (!is_insert ? "/" + current_toto_id : ''),
        data: {
            text : this.new_todo_text,
            priority : this.new_todo_priority
        },
    }).then((response) => {
        this.new_todo_text= ''
        this.new_todo_priority= ''
        this.loadTodosRows()
        popupAlert( 'Todo ' + (is_insert ? 'added' : 'updated') + ' successfully !', 'success' )
    }).catch((error) => {
        var validationErrors= convertObjectToArray(error.response.data.errors.text)
        
        this.validation_errors_text= ''
        validationErrors.map((next_error, index) => {
            if(next_error && typeof next_error[1] != "undefined" ) {
                this.validation_errors_text += '<li>'+next_error[1]+'</li>'
            }
        })

        popupErrorMessage(error.response.data.message)
    });

},

有了它,我会根据需要显示成功和失败的消息,但我看到它有很大的缺点,因为我使用 livewire,如果可能的话,我想在这里使用 livewire...希望我清楚地解释了我想要什么...

谢谢!

4

1 回答 1

1

使用 Alpine.js 和 axios 你可以做这样的事情,注意我不确定 , 是否this_frontend_home_url会被定义。this_vote_idthis_csrf_token

<div x-data="quiz()">
  <div>
    <div class="table-responsive">
      <table class="table text-primary">
        @foreach($quizQualityOptions as $key=>$next_quiz_quality_option)
        <tr>
          <td>
            <input x-model="selected_quiz" class="" type="radio" name="quiz_quality_radio"
              id="quiz_quality_radio_{{ $next_quiz_quality_option }}" value="{{ $key }}">
            <label class="col-form-label"
              for="quiz_quality_radio_{{ $next_quiz_quality_option }}">{{ $next_quiz_quality_option }}</label>
          </td>
        </tr>
        @endforeach
      </table>
    </div>

    <div class="row p-3">
      <a class="btn btn-primary a_link" @click="submitQuizQuality()">Rate !</a>
    </div>
  </div>
</div>
<script>
  function quiz() {
    return {
      selected_quiz: null,
      submitQuizQuality() {
        const url = this_frontend_home_url + "/make-quiz-quality";
        axios.post(url, {
          quiz_quality_id: this.selected_quiz,
          vote_id: this_vote_id, // no idea where this is coming from,
          _token: this_csrf_token // no idea where this is coming from
        }).then(() => {
          // reset "checked" state
          this.selected_quiz = null;
          frontendVote.showQuizQualityResults();
          popupAlert("Thank you for rating ! Your rate was added!", 'success');
        }).catch(error => {
          // reset "checked" state
          this.selected_quiz = null;
          if (error && error.response) {
            popupAlert(error.response.message, 'danger')
          }
        });
      }
    }
  }
</script>
于 2020-08-21T11:22:29.290 回答