Laravel 5 如何让控制器显示简单的消息框或警报?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35234214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5 how to get controller display simple message box or alert?
提问by Nikanor
Cannot find solution to this simple problem, i just do some voting app, and if users votes I would like to show simple alert like "Thanks" , but I cannot find the way to do it from the controller? I have tried the simple jQuery code like this but it's not working.
找不到这个简单问题的解决方案,我只是做一些投票应用程序,如果用户投票,我想显示像“谢谢”这样的简单警报,但我找不到从控制器中做到这一点的方法?我已经尝试过像这样的简单 jQuery 代码,但它不起作用。
echo "<script>alert('You have already voted');</script>";
Any simple solutions?
有什么简单的解决办法吗?
public function voting()
{
$ip=$_SERVER['REMOTE_ADDR'];
$id = Input::get('msg_id');
$vote = Input::get('vote');
$count = Voting::wheremes_id_fk($id)->whereip_add($ip)->count();
if($count==0)
{
if($vote == "up")
{
Project::whereid($id)->increment('up');
Voting::insert(
array('mes_id_fk' => $id, 'ip_add' => $ip )
);
}
else if ($vote=="down") {
Project::whereid($id)->decrement('down');
Voting::insert(
array('mes_id_fk' => $id, 'ip_add' => $ip )
);
}
}
else {
// How to popup "thanks" alert??
}
}
回答by Jilson Thomas
If you are using ajax to do the vote, return a json
response and use JavaScript
to respond to the json
response.
如果您使用ajax进行投票,则返回json
响应并使用JavaScript
响应json
响应。
example:
例子:
public function vote()
{
//your voting code
return Response::json(['success'=>true]);
}
and in your JavaScript
, check the json
并在您的 中JavaScript
,检查 json
$.post('/vote/', { id: 123 }, function(data){
if(data.success== true)
{
alert('Thanks for voting);
}
}
If you are not using ajax, simply use the Session flash.
如果您不使用 ajax,只需使用 Session flash。
i.e., from your controller,
即,从您的控制器,
public function vote()
{
//your voting code
Session::flash('msg', 'Thanks for voting');
return Redirect::back();
}
and from View,
从视图中,
@if(Session::has('msg'))
{{Session::get('msg')}}
@endif