maf*_*tis 7 ajax jquery-ui jquery-ui-sortable laravel
我尝试为我的类别制作可排序函数,我正在使用 JQuery UI
category_id为null,则表示该类别为parent.(在我的情况下,我使用category_id而不是parent_id只是不同的命名)Parent->child 1->child 1
childscategory_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
Run Code Online (Sandbox Code Playgroud)
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);
}
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
route
Route::post('/categorysort/{id}','CategoryController@UpdatecategoryparentByAjax')->name('categorysort');
Run Code Online (Sandbox Code Playgroud)
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,
]);
}
}
Run Code Online (Sandbox Code Playgroud)
PS:我知道我缺少
category_id数据li's的原因是因为我不知道该如何使用它,因为我之前在我的问题中提到我的功能不支持(所以我需要你的帮助).
screenshot
这可能是因为您没有保护 agaisnt csrf,这在执行发布请求时是强制性的,因此,正如laravel 文档所解释的,您可以通过将其添加到 html 来解决:
<meta name="csrf-token" content="{{ csrf_token() }}">
Run Code Online (Sandbox Code Playgroud)
然后在你的 ajax 中你只需要将它附加为标题。
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/categorysort/'+ itemID ,
type: 'POST',
dataType: 'json',
data: {itemID: itemID, itemIndex: itemIndex},
});
Run Code Online (Sandbox Code Playgroud)
另外,您只收到 1 个 id,所以我猜您想要做的事情是根据父类进行排序,因此您应该只选择父类li,这样您的控制器将收到 1 个 id 而不是 2 个,因为您正在做的事情现在是/categorysort/{parentId}/{childId},您需要的是/categorysort/{id},因此不必选择所有类别,只需选择顶级父类别:
$.map($(this).find('.parent'), function(el)
Run Code Online (Sandbox Code Playgroud)