我尝试为我的类别制作可排序的功能,我正在使用 JQuery UI
逻辑
category_id
为 null 表示该类别是父类别。(就我而言,我使用
category_id
而不是 parent_id
只是不同的命名)
Parent->child 1->child 1
childs
我尝试做的
更新
category_id
当我通过 Ajax 删除和删除我的类别之一时的列问题
404
网络错误 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: I'm aware that there is missing
category_id
data in myli's
the reason i didn't put that is because I didn't know how to should I use it exactly, as I mentioned before in my issues my function doesn't support that yet (so I need your helps please).
screenshot
谢谢。
最佳答案
这可能是因为您没有保护 agaisnt csrf,这在执行 post 请求时是强制性的,如 laravel docs解释您可以通过将其添加到您的 html 来解决:
<meta name="csrf-token" content="{{ csrf_token() }}">
然后在您的 ajax 中,您只需要将其附加为标题。
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/categorysort/'+ itemID ,
type: 'POST',
dataType: 'json',
data: {itemID: itemID, itemIndex: itemIndex},
});
此外,您只收到 1 个 id,所以我想您要做的是根据父级进行排序,因此您应该只选择
li
对于父类,这样您的 Controller 将收到 1 个 id 而不是 2 个,因为您现在正在做的是 /categorysort/{parentId}/{childId}
你需要的是 /categorysort/{id}
,所以不要选择所有类别,只需选择顶部的父类别:$.map($(this).find('.parent'), function(el)
关于ajax - 可在 Laravel 中的 null id 上排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50672842/