ajax - 可在 laravel 中的空 id 上排序
问题描述
我尝试为我的类别制作可排序功能并且我正在使用JQuery UI
逻辑
- 如果类别
category_id
为空,则表示该类别是父类别。(在我的情况下,我使用category_id
而不是parent_id
只是不同的命名) - 类别最多 2 深喜欢
Parent->child 1->child 1 childs
我尝试做什么
category_id
当我通过 Ajax 删除我的类别之一时更新列
问题
- 我
404
在网络上遇到错误 - 我的函数不支持 null
category_id
代码
@foreach($Categorys as $cat)
//parent (deep 0)
<li class="parent" id="{{$cat->id}}">
{{$cat->title}}
//first child (deep 1)
@if(count($cat->childs))
@foreach($cat->childs as $child)
<li style="margin-left:20px !important;" class="firstchild" id="{{$child->id}}">
{{$child->title}}
//first child child (deep 2)
@if(count($child->childs))
@foreach($child->childs as $childdd)
<li style="margin-left:40px !important;" class="secondchild" id="{{$childdd->id}}">
{{$childdd->title}}
</li>
@endforeach
@endif
</li>
@endforeach
@endif
</li>
@endforeach
Ajax
$(function() {
$('.mytest').sortable({
stop: function() {
$.map($(this).find('li'), function(el) {
var itemID = el.id;
var itemIndex = $(el).index();
if (itemID) {
$.ajax({
url: '{{ url('
categorysort ') }}/' + encodeURI(itemID),
type: 'POST',
dataType: 'json',
data: {
itemID: itemID,
itemIndex: itemIndex
},
});
} else {
console.log(data);
}
});
}
});
});
route
Route::post('/categorysort/{id}','CategoryController@UpdatecategoryparentByAjax')->name('categorysort');
controller
public function UpdatecategoryparentByAjax(Request $request, $id)
{
$categories = Category::orderby('id', 'desc')->get();
$itemID = $request->input('itemID');
$itemIndex = $request->input('itemIndex');
foreach ($categories as $category) {
$category->where('id', $itemId)->update([
'category_id' => $itemIndex,
]);
}
}
PS:我知道我没有输入的原因是
category_id
我的数据丢失li's
了,因为我不知道应该如何准确地使用它,正如我之前在我的问题中提到的那样,我的功能不支持然而(所以我需要你的帮助)。
screenshot
解决方案
看到你的评论后encodeURI(itemID)
,我知道问题是你的route.php
。
我在网络上收到 404 错误
您需要使用可选参数更新您的路线:
Route::post(
// Add {second_id?}. This is an "optional parameter".
'categorysort/{first_id}/{second_id?}',
'CategoryController@UpdatecategoryparentByAjax'
)->name('categorysort');
因此,您可以访问:
mydomain.test/categorysort/1
mydomain.test/categorysort/1/2
如果您需要第三个id
,请添加更多可选参数,如下所示:
Route::post(
'categorysort/{first_id}/{second_id?}/{third_id?}',
'CategoryController@UpdatecategoryparentByAjax'
)->name('categorysort');
因此,您可以访问:
mydomain.test/categorysort/1
mydomain.test/categorysort/1/2
mydomain.test/categorysort/1/2/3
如果你想做first_id
同样的事情,只需在like?
之后添加。first_id
{first_id?}
我的函数不支持 null category_id
更新您的路线后,您只需要致电:
public function UpdatecategoryparentByAjax(Request $request, $first_id, $second_id, $third_id)
{
// $first_id access your 1st ID
// $second_id access your 2nd ID
// $third_id access your 3rd ID
// Do some logic here..
}