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

时间:2018-01-02 17:18:11

标签: php laravel controller routes href

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

刀片

<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函数的运行。

1 个答案:

答案 0 :(得分:2)

为什么不使用Ajax调用呢?

<强> HTML:

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

<强> ROUTE:

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