在 Laravel 中,我需要指定行 ID 作为请求 URL 的一部分才能更新它,例如:http://localhost/contacts/16
问题出在使用 jQuery-Tabledit 时,因为它在初始化(页面加载时)时需要 URL。
那么问题是,如何在 jQuery-Tabledit 中将当前行 ID 设置为 URL?
HTML:
<table class="table table-striped table-bordered" id="contactsTable">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th class="tabledit-toolbar-column"></th>
</tr>
</thead>
<tbody>
@if($contacts)
@foreach ($contacts as $contact)
<tr id="{{$contact->id}}">
<td><span class="tabledit-span tabledit-identifier">{{$contact->id}}</span><input class="tabledit-input tabledit-identifier" type="hidden" name="id" value="{{$contact->id}}" disabled=""></td>
<td class="tabledit-view-mode"><span class="tabledit-span">{{$contact->first_name}}</span><input class="tabledit-input form-control input-sm" type="text" name="first_name" value="{{$contact->first_name}}" style="display: none;" disabled=""></td>
<td class="tabledit-view-mode"><span class="tabledit-span">{{$contact->last_name}}</span><input class="tabledit-input form-control input-sm" type="text" name="last_name" value="{{$contact->last_name}}" style="display: none;" disabled=""></td>
</tr>
@endforeach
@endif
</tbody>
JavaScript:
<script>
$( document ).ready(function() {
$('#contactsTable').Tabledit({
url: 'http://localhost/contacts/22',
saveButton: false,
columns: {
identifier: [0, 'id'],
editable: [[1, 'first_name'], [2, 'last_name']]
}
});
});
如您所见,url: ' http://localhost/contacts/22 ' 是问题所在。上面的代码按预期工作,但仅更新第 22 行,因为 jQuery-Tabledit URL 已固定编码为第 22 行。
最佳答案
我假设您的 jquery 位于当前 Blade 内。因此这些括号:{{ }}, {!!仅当您使用扩展名
.blade.php 时,!!}
才会被视为模板。
因此,您可以做的就是简单地使用blade 使用括号来回显联系人 ID
。
<script>
$( document ).ready(function() {
$('#contactsTable').Tabledit({
url: 'http://localhost/contacts/'+{!! $contact->id !!},
saveButton: false,
columns: {
identifier: [0, 'id'],
editable: [[1, 'first_name'], [2, 'last_name']]
}
});
});
或者只是将联系人集合序列化为 json:
$('#contactsTable').on('click', function(){
let contacts = {!! $contacts->toJson() !!};
// now you can access all attributes that are defined in Contacts model
// example contact id
let contact_id = contacts.id;
}
关于javascript - 如何使用 jQuery-Tabledit 和 Laravel 更新表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47851397/