简体   繁体   English

如何生成访问错误和错误消息,将用户留在页面上?

[英]How can I generate access error and error message, leaving user on the page?

In laravel / jquery apps if I need to make checks if user is logged I make in controller:在 laravel / jquery 应用程序中,如果我需要检查用户是否已登录,我在 controller 中进行:

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

as I do not need to leave the user from the page, but only restrict some functionality I show error message above using bootstrapGrowl library.因为我不需要让用户离开页面,而只限制一些功能,所以我使用 bootstrapGrowl 库在上面显示错误消息。 Now with laravel 7 /livewire 1.3 / turbolinks:5 / alpine@v2 I search how can I generate error and show similar error message, leaving user on the page?现在使用 laravel 7 /livewire 1.3 / turbolinks:5 / alpine@v2 我搜索如何生成错误并显示类似的错误消息,让用户留在页面上?

UPDATED:更新:

Let me explain it with detailed example: In laravel / jquery apps I have in JS code:让我用详细的例子来解释一下:在 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'
    }
});

and relative action in control:和控制中的相对动作:

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)

and in case of error generated in error block I show message with function popupAlert (implemented with bootstrapGrowl), without leaving the page.如果在错误块中生成错误,我会在不离开页面的情况下显示带有 function popupAlert 的消息(通过 bootstrapGrowl 实现)。 That is what I want to make in livewire / turbolinks / alpine app.这就是我想在 livewire / turbolinks / alpine 应用程序中制作的内容。 How can I do it?我该怎么做?

UPDATED # 2:更新#2:

That is just listing of items user can vote for:这只是用户可以投票的项目列表:

<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>

with 2 restrictions:有2个限制:

  1. User must be logged用户必须登录
  2. Any logged user can vote only once these 2 errors were genarated at server.只有在服务器生成这 2 个错误后,任何登录用户才能投票。

UPDATED # 3:更新#3:

I found decision with using of axios, like:我发现使用 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)
    });

},

With it I show message both on success and failure as I need but I see big disadvantage with it as I use livewire and I would like to use livewire here, if that is possible... Hope I explained what I want clearly...有了它,我会根据需要显示成功和失败的消息,但我看到它有很大的缺点,因为我使用 livewire 并且我想在这里使用 livewire,如果可能的话......希望我清楚地解释了我想要什么......

Thanks!谢谢!

With Alpine.js and axios you could do something like this, note that I'm not sure whether or not this_frontend_home_url , this_vote_id and this_csrf_token will be defined.使用 Alpine.js 和 axios 你可以做这样的事情,注意我不确定this_frontend_home_urlthis_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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何滚动到 livewire laravel 中的第一个验证错误消息 - how to scroll to first validation error message in livewire laravel 未出现错误消息,请验证数组 - error message not appearing, validate array 如何在 laravel livewire 中自定义超时 504 错误页面? - How to customize the timeout 504 error page in laravel livewire? Laravel 自定义规则的自定义验证错误信息 - Laravel custom rule's custom validation error message 后端(Laravel Jetstream)发生(验证)错误后,如何返回注册页面显示错误状态? - After a (validation) error occurs in the backend (Laravel Jetstream), how to return back to register page showing the error as status? 如何在 Laravel livewire 中使用 foreach 循环仅访问特定的输入字段? - How can I access only specific input fields using foreach loop in Laravel livewire? 使用整页组件时如何更改页面标题-Livewire - How can I change page title when I use full page components-Livewire Livewire Laravel - 每次我尝试调用一个方法时,我都会收到一个带有 404 页面的 div livewire-error - Livewire Laravel - Every time I try to call a method, I get a div livewire-error with 404 page Laravel livewire:livewire/message/postcart 500(内部服务器错误) - Laravel livewire : livewire/message/postcart 500 (Internal Server Error) Livewire 错误:公共属性 [消息] 必须是类型:[数字、字符串、数组、null 或布尔值] - Livewire Error: public property [message] must be of type: [numeric, string, array, null, or boolean]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM