Php 如何在视图中显示消息成功或失败使用响应?(拉威尔5.3)
我对控制器的销毁方法如下:Php 如何在视图中显示消息成功或失败使用响应?(拉威尔5.3),php,laravel,session,laravel-5.3,Php,Laravel,Session,Laravel 5.3,我对控制器的销毁方法如下: public function destroy($id) { try{ if($this->product_service->destroy($id)){ return $this->respond(['status' => 'success']); }else{ return $this->respond(['status' => 'faile
public function destroy($id)
{
try{
if($this->product_service->destroy($id)){
return $this->respond(['status' => 'success']);
}else{
return $this->respond(['status' => 'failed']);
}
}catch (\Exception $e){
return $this->respondWithError();
}
}
@if (session('status')=='success')
<div class="alert alert-success">
<ul>
<li>Delete Success</li>
</ul>
</div>
@elseif (session('status')=='failed')
<div class="alert alert-warning">
<ul>
<li>Delete Failed</li>
</ul>
</div>
@endif
public function respond($data, $headers=[])
{
return response()->json($data,$this->getStatusCode(), $headers);
}
我的看法是这样的:
public function destroy($id)
{
try{
if($this->product_service->destroy($id)){
return $this->respond(['status' => 'success']);
}else{
return $this->respond(['status' => 'failed']);
}
}catch (\Exception $e){
return $this->respondWithError();
}
}
@if (session('status')=='success')
<div class="alert alert-success">
<ul>
<li>Delete Success</li>
</ul>
</div>
@elseif (session('status')=='failed')
<div class="alert alert-warning">
<ul>
<li>Delete Failed</li>
</ul>
</div>
@endif
public function respond($data, $headers=[])
{
return response()->json($data,$this->getStatusCode(), $headers);
}
我建议您使用此软件包: 请阅读那里的文档,解释得很好 或 如果要使用自定义代码执行此操作: 控制器
public function destroy($id)
{
if($this->product_service->destroy($id)){
return view('viewname', ['class' => 'success', 'message' => 'Delete Success']);
} else{
return view('viewname', ['class' => 'success', 'message' => 'Delete Failed']);
}
}
查看:
<div class="alert alert-{{ $class }}">
<ul>
<li>{{ $message }}</li>
</ul>
</div>
- {{$message}}
使用:
$request->session()->flash('status', 'Task was successful!');
您只需拨打:
return \Redirect::back()->with('status', 'your status here...');
应该是这样
或者,如果希望返回json对象
,可以使用Response:json
,使用AJAX
非常方便,如下所示:
return \Response::json(['status' => 'your status here...'], 200);
errorsHtml = '<div class="alert alert-danger"><ul>';
$.each(responseText, function(k, v){
errorsHtml += '<li>' + v + '</li>';
});
errorsHtml += '</ul></div>';
$("#feedback").append(errorsHtml);
然后,您可以使用ajax
在视图上捕获状态,如下所示:
return \Response::json(['status' => 'your status here...'], 200);
errorsHtml = '<div class="alert alert-danger"><ul>';
$.each(responseText, function(k, v){
errorsHtml += '<li>' + v + '</li>';
});
errorsHtml += '</ul></div>';
$("#feedback").append(errorsHtml);
我想使用$this->响应。不是其他人。它不能吗?不,它不能,。。你在哪里读到过这种方法?你能给出URL吗?我的控制器扩展了ApiController。在我的ApiController中,存在这样的方法:public function response($data,$headers=[]){return response()->json($data,$this->getStatusCode(),$headers);}
您实际上并没有在任何地方向会话添加任何内容。您还将返回json响应,因此很难判断视图何时被准确加载。