How to pass data from controller to view in laravel?

问题: I need to pass data from controller to view this is code : Controller : function requete() { $id = Str::random(); return view('Demo.requete', compact('id'));...

问题:

I need to pass data from controller to view this is code :

Controller :

function requete()
{
    $id = Str::random();  
    return view('Demo.requete', compact('id'));
}

View :

$(document).ready(function() {   
    $.ajax({
        url: "{{ route('support.requete') }}",
        method: "get",
        data: data,
        dataType: "json",
        success: function(data)
        {
            $('#code').html(data.id);//nothing happens here
        }
    });
});

I keep getting this error :

enter image description here


回答1:

You can do :

return view('Demo.requete', compact('id'));

Then you can use {{ $id }} directly in the blade file.

Update :

You are using ajax so you will need a json response :

return response()->json(compact('id'), 200);

Then you can do in ajax success :

$('#code').html(data.id);

回答2:

You shouldn’t return a view with an Ajax request, that should be a different route to hit with the $.ajax get request. Laravel can then return JSON responses and you can use that in your success callback.

return response()->json([‘id’ => $id]);

回答3:

You shouldn't use echo in the view. You shouldn't use ajax to get the view (unless you want to receive HTML and it does not seem the case here) You should have a different endpoint for your ajax request if you want to fetch the data asynchronously otherwise you can just return the view with all the data you need.


回答4:

In case of ajax, try returning response json

function requete()
{
    $id = Str::random();
    return response()->json([
     "id" => json_encode($id)
   ]);
}
  • 发表于 2019-03-01 17:52
  • 阅读 ( 196 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除