简体   繁体   English

Laravel 5如何让控制器显示简单的消息框或警报?

[英]Laravel 5 how to get controller display simple message box or alert?

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??
    }
}

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。

ie, from your controller, 即从您的控制器,

public function vote()
{
  //your voting code
  Session::flash('msg', 'Thanks for voting');
 return Redirect::back();
}

and from View, 在View中

@if(Session::has('msg'))
  {{Session::get('msg')}}
@endif

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM