weixin_33704234 2019-12-21 05:24 采纳率: 0%
浏览 43

带消息的Ajax重定向

I'm trying to implement Ajax call in Laravel project. Currently I'm looking for a way to display success/error messages after Ajax successfully execute something & redirect the page. In Laravel controller, usually I can do it like this:

if($patient->wasRecentlyCreated){
    return redirect('/patients')->with('success','New patient data saved');
} else {
    return redirect('/patients')->with('error','Patient already exist');
}

As in the blade view, I have added the message section in the layout page (so that the message will appear on the top of redirected page) :

@if(count($errors)>0)
    @foreach ($errors->all() as $error)
        <div class="alert alert-danger">
            {{$error}}
        </div>
    @endforeach
@endif

@if(session('success'))
    <div class="alert alert-success">
        {{session('success')}}
    </div>
@endif
@if(session('error'))
    <div class="alert alert-danger">
        {{session('error')}}
    </div>
@endif

The case with Ajax call, I'm able to pass the redirect target URL from Laravel controller but I don't know how to pass the success/error message to Ajax. Below is the sample of Laravel controller I have made to handle the Ajax:

if($settlement->wasRecentlyCreated){
    return url('/patients');
}

And in Ajax section, I can redirect using window.location :

$.ajax({
    url: "/createsettlement",
    type: 'post',
    data: {
        billing_id      : billing_id,
        prices          : prices,
        _token          : '{{csrf_token()}}'
    },
    success: function (data) {
        console.log(data);
        window.location = data;
    },

Any idea how to pass the success/error messages while Ajax do page redirection?

  • 写回答

2条回答 默认 最新

  • ?Briella 2019-12-21 07:27
    关注

    OK. you can do the redirection and show in the same time.

    But considering that ajax is JS you can set a timeout for redirection, i.e.

    
        $('#error-alert').text('The text you want to display').show();
        setTimeout(() => {
            window.location =  url;
        }, 3000); //this case waits 3 secs to redirect to the page you want
    

    Hope it helps

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?