2017-06-16 64 views
-1

如果ajax成功与否,我想显示一条消息。 该代码到目前为止,但我想添加一些消息。Laravel Ajax显示消息

我的控制器删除功能:

public function destroy(Request $request, $streamID = 0) 
{ 
    $stream = Stream::find($streamID); 

    if($stream) 
    { 
     $stream->delete(); 
     File::delete($stream->image); 
     return redirect()->route('stream.index')->with('success', 'Hooray'); 
    } 
    else 
    { 
     return redirect()->route('stream.index')->with('success', 'Not Hooray'); 
    } 
} 

而阿贾克斯成功和错误部分:

 success: function(data) { 
      // show message? 
     }, 
     error: function(data) { 
      // show message? 
     } 
+0

而且怎么能帮到你?告诉你关于'alert'的功能吗? –

+0

你可以使用Flash数据https://laravel.com/docs/5.4/session#flash-data – mfgabriel92

+0

而不是返回redirect() - > route('stream.index') - > with('success','Hooray '); return response() - > json(['success'=>'Hooray']); – sunilwananje

回答

1

,而不是从你的PHP代码重新定向的,从你的Ajax功能重定向和发送JSON响应您的阿贾克斯功能为

public function destroy(Request $request, $streamID = 0) 
{ 
    $stream = Stream::find($streamID); 

    if($stream) 
    { 
     $stream->delete(); 
     File::delete($stream->image); 
     return response() ->json(['code'=>200,'success' => 'Hooray']); 
    } 
    else 
    { 
     return response() ->json(['code'=>400,'success' => 'Not Hooray']) 
    } 
} 

并在你的ajax成功函数

success: function(response) { 
     alert(response.success); 
     window.location.href = 'stream.index'; 
}, 
error: function(data) { 
     // show message? 
} 
+0

你会如何在laravels flash讯息样式中显示它(带有绿色/红色背景的框) – utdev

+0

试过你的代码没有工作 – utdev

0

我以前的答案更新到这一点:

.... 
    if($stream) { 
     $stream->delete(); 
     File::delete($stream->image); 
     return response()->json(['code'=>200,'success' => 'Hooray'],200); 
} 
    else { 
      return response()->json(['code'=>400,'success' => 'Not Hooray'],200); 
    } 
+0

嗨,但是在哪里/如何在ajax中添加成功消息? – utdev

+0

@utdev我发布了你的评论的答案希望它有帮助 – hazelcodes

0

如果你使用的引导,这种添加任何你想要的警报显示

<div id="ajax-alert" class="alert" style="display:none"></div> 

修改你的脚本这:

success: function(response){ 
    If(response.code === 200) { 
     $('#ajax-alert').addClass('alert-sucess').show(function(){ 
      $(this).html(response.success); 
     }); 
    } 
    If(response.code === 400){ 
     $('#ajax-alert').addClass('alert-danger').show(function(){ 
      $(this).html(response.success); 
     }); 
    } 
}, 
error: function(data) { 
    alert ('Ajax run unsuccessful'); 
}