我看到有许多类似的问题,就像这一个,但没有一个问题给了我正是我想要的。
我有一个JQuery可排序的记录列表。当用户向上或向下移动记录(以便重新排序记录)时,JQuery的.ajax()函数应该获取此数据并将其传递给名为second()的Laravel控制器函数。然后函数second()应该获取该数据,并且对于每一行,提取其位置(由整数表示)并更新数据库表中的“order”列。然后,记录应按顺序显示在视图上。
我将所有工作都推进到将数据传递给second()函数的地步:
路线:
Route::post( '/income-category/second', array(
'as' => 'income-category.second',
'uses' => 'IncomeCategoryController@second'
));
JQuery的:
$("#sortable").sortable({
update : function () {
var serial = $('#sortable').sortable('serialize'); //split up each li into an array item
$("body").css("cursor", "progress");
$.ajax({
url: BASE_URL + "income-category/second",
type: "post",
data: {serial: serial},
cache: false,
dataType: 'json',
success: function(info){
console.log(info);
},
error: function(){
alert("there's an error with AJAX");
}
});
}
});
控制器(不完整):
public function second(){
$orders = Input::all();
foreach($orders as $order){
$folge[] = $order;
}
return Response::json($folge);
}
经过一些故障排除后,我终于在控制台上弹出了AJAX输出。事实证明,如上所示的foreach循环将抛出“无效的foreach参数”错误,因为 - 我假设 - 在以下对象中只有一个键:
Object {serial: "item[]=2&item[]=3&item[]=1&item[]=4&item[]=5"}
当我在其他非Laravel项目中完成此操作时,一个简单的foreach($ _ POST ['item']作为$ item)起作用。现在它没有。
HTML摘录:
<tbody id="sortable">
@if(isset($_GET['category']))
{{ Form::open(array('route'=> array('income-category.update', $_GET['category']), 'method'=>'PUT')) }}
@foreach($categories as $catId=>$catVal)
@if($_GET['category'] == $catId)
<tr id="{{ 'item_'. $_GET['category'] }}">
<td>{{ Form::text('category_name', $catVal) }} <br>{{ $errors->first('category_name') }}</td>
<td>
{{ Form::submit('Save', ['category'=>$catId, 'class'=>'btn btn-success btn-sm', 'name' => 'submit_' . $_GET['category'], 'title'=>'Save']) }}
{{ link_to('income-category', 'Cancel', ['class'=>'btn btn-default btn-sm', 'title'=>'Cancel']) }}
</td>
</tr>
@else
<tr>
<td>{{ $catVal }}</td>
<td>{{ HTML::linkAction('IncomeCategoryController@index', '', ['category'=>$catId], ['class'=>'glyphicon glyphicon-pencil shadow pointer', 'title'=>'Edit']) }} {{ Form::button('', ['category'=>$catId, 'type'=>'submit', 'class'=>'glyphicon glyphicon-trash shadow pointer', 'name' => 'delete' . $_GET['category'], 'title'=>'Delete', 'onclick' => 'confirm("For now this is just going to delete no matter what you pick.")']) }} </td>
</tr>
@endif
@endforeach
{{ Form::close() }}
...
...
我真的很困惑,所以我希望这有点意义。