问题:
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 :
回答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)
]);
}