重新路由Laravel后,防止重新加载页面表单

问题描述 投票:1回答:1

我正在实施帐户验证,部分内容正在重新发送电子邮件验证。

<a href="/register/resend/{{ $objUser->id }}">@lang('localization.clickHere')</a>@lang('localization.toResendEmail')

路线/网络

Route::get('register/resend/{id}','Auth\VerificationController@resend');

调节器

public function resend($id, Request $request)
{   
    $user = User::where('id',$id)->firstOrFail();
    Mail::to($user->email)->queue(new ConfirmRegistration($user));

    $messenger = new Messenger($user);
    $messenger->sendSuccess(__(trans('localization.emailSentSuccessfully')));

    return back();
} 

我遇到的问题是,每当我触发href时页面都会重新加载(如预期的那样),这会导致Controller发送的消息立即消失。

有没有办法阻止页面重新加载,但仍然触发route?我尝试添加onclick="return false;",但这似乎阻止resend功能运行。

php laravel controller routes href
1个回答
2
投票

为什么不使用Ajax调用呢?

HTML:

<a href="javascript:void(0)" onclick="mailme(this)" user-id="{{ $objUser->id }}">@lang('localization.clickHere')</a>@lang('localization.toResendEmail')

路线:

Route::get('register/resend','Auth\VerificationController@resend');

控制器:

public function resend(Request $request)
{   
    $user = User::where('id',$request->id)->firstOrFail();
    Mail::to($user->email)->queue(new ConfirmRegistration($user));

    $messenger = new Messenger($user);
    $messenger->sendSuccess(__(trans('localization.emailSentSuccessfully')));

    return response()->json('success');
} 

JS(没有JQuery):

mailme = function(obj){
  var userID = obj.getAttribute('user-id')
  var xhttp;
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log(this.responseText);
    }
  };
  var params = JSON.stringify({ id: userID });

  xhttp.setRequestHeader("Content-type", "application/json; charset=utf-8");
  xhttp.setRequestHeader("Content-length", params.length);
  xhttp.setRequestHeader("Connection", "close");

  xhttp.open("GET", '{{url("settings/register/resend")}}', true);

  xhttp.send(params);
}

JS(JQuery):

mailme = function(obj){
    var userID = $(obj).attr('user-id')
    $.ajax({
        type : 'Get',
        data : {
            id: userID
        },
        url : '{{url("settings/register/resend")}}',
        dataType : 'json',
        success: function(data){
            console.log(data)
        }
    });
}

这样,您将触发该功能,而无需重新加载页面以将请求发送到服务器。请求通过xhttp发送

© www.soinside.com 2019 - 2024. All rights reserved.