简体   繁体   中英

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'));
}

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 :

在此处输入图片说明

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);

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.

Yo

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

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.

In case of ajax, try returning response json

function requete()
{
    $id = Str::random();
    return response()->json([
     "id" => json_encode($id)
   ]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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