我在 Laravel 中有一个数据表,这是我的代码
$(function() {
var user_id = $(this).data('user_id');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $('.data-table').DataTable({
paging: true,
info: true,
autoWidth: false,
responsive: true,
processing: true,
serverSide: true,
ajax: "{{ route('detail.user', 'user_id')}}",
columns: [{
data: 'DT_RowIndex',
name: 'DT_RowIndex',
orderable: false,
searchable: false,
},
{
data: 'title',
name: 'title',
orderable: false,
},
{
data: 'content',
name: 'content',
orderable: false,
visible: false,
},
{
data: 'progress',
name: 'progress'
},
{
data: 'status',
name: 'status'
},
{
data: 'kpi',
name: 'kpi'
},
{
data: 'target_selesai',
name: 'target_selesai'
},
{
data: 'action',
name: 'action',
orderable: false,
searchable: false
},
]
});
$('body').on('click', '.detailProduct', function() {
...
});
$('#saveBtn').click(function(e) {
...
});
$('body').on('click', '.deleteProduct', function() {
...
});
});
我想从 url 参数中获取 user_id 值(例如: http://127.0.0.1:8000/detail/1000000004 ),我已经尝试过上面的代码,但它会返回空值。
好像我写了错误的代码来获取 url 参数。因为,如果我将 ajax: "{{ route('detail.user', 'user_id')}}",
更改为 ajax: "{{ route('detail.user', '1000000004')}}",
,程序将按预期工作。我该怎么办?提前致谢
您不能使用 JavaScript 在 PHP 代码中设置变量。您不应在动态 JavaScript 代码上使用 PHP 代码。有两种选择:
使用静态路径代替 Laravel 路由,只需将 ajax: "{{ route('detail.user', 'user_id')}}"
改为 ajax: "/detail/"+user_id
使用 Laravel 刀片视图 arg 发送 user_id
变量。在您的控制器上定义 user_id,如下所示:
return view('index',
['user_id', 1000000004]
);
然后在刀片上调用它作为 php 变量 ($user_id
) 示例 ajax: "{{ route('detail.user', $user_id)}}"